当我试图在Stack Overflow中回答一个关于R的问题时,我的大部分时间都花在试图重建作为示例的数据上(除非问题作者足够友好地将它们作为R代码提供)。
所以我的问题是,如果有人只是问了一个问题,并以以下方式给出了他的样本数据帧:
a b c
1 11 foo
2 12 bar
3 13 baz
4 14 bar
5 15 foo您是否有一个技巧或函数可以轻松地将其导入到R会话中,而不必键入整个data.frame()指令?
提前感谢您的任何提示!
PS :抱歉,如果我的问题标题中的“查询”一词不是很好,但似乎您不能在Stack overflow中的问题标题中使用“问题”一词:-)
发布于 2012-06-01 19:21:59
也许textConnection()就是你想要的:
R> zz <- read.table(textConnection("a b c
1 11 foo
2 12 bar
3 13 baz
4 14 bar
5 15 foo"), header=TRUE)
R> zz
a b c
1 1 11 foo
2 2 12 bar
3 3 13 baz
4 4 14 bar
5 5 15 foo
R> 它允许你将文本作为一个“连接”来阅读。您也可以只复制和粘贴,但从剪贴板访问更依赖于操作系统,因此可移植性较差。
发布于 2012-06-01 21:02:22
最新版本的R现在提供了比textConnection更低的击键选项,用于将列数据输入到read.table和朋友中。面对这种情况:
zz
a b c
1 1 11 foo
2 2 12 bar
3 3 13 baz
4 4 14 bar
5 5 15 foo可以简单地在zz后面插入:<- read.table(text=",删除回车符,然后在最后一个foo之后插入", header=TRUE),然后键入enter。
zz<- read.table(text=" a b c
1 1 11 foo
2 2 12 bar
3 3 13 baz
4 4 14 bar
5 5 15 foo", header=TRUE)还可以使用scan有效地输入纯数字或纯字符向量条目的长序列。面对: 67 75 44 25 99 37 6 96 77 21 31 41 5 52 13 46 14 70 100 18,您可以简单地输入:zz <- scan()并按enter键。然后粘贴选定的数字并再次按回车键,也许第二次按回车键会导致两次回车,控制台应该会响应"read 20 items“。
> zz <- scan()
1: 67 75 44 25 99 37 6 96 77 21 31 41 5 52 13 46 14 70 100 18
21:
Read 20 items"character“任务。粘贴到控制台并编辑掉无关的换行符并添加引号后,按enter键
> countries <- scan(what="character")
1: 'republic of congo'
2: 'republic of the congo'
3: 'congo, republic of the'
4: 'congo, republic'
5: 'democratic republic of the congo'
6: 'congo, democratic republic of the'
7: 'dem rep of the congo'
8:
Read 7 items发布于 2012-06-01 19:27:41
你也可以要求提问者使用the dput function,它以一种可以直接复制粘贴到R中的方式转储任何数据结构。
> zz
a b c
1 1 11 foo
2 2 12 bar
3 3 13 baz
4 4 14 bar
5 5 15 foo
> dput(zz)
structure(list(a = 1:5, b = 11:15, c = structure(c(3L, 1L, 2L,
1L, 3L), .Label = c("bar", "baz", "foo"), class = "factor")), .Names = c("a",
"b", "c"), class = "data.frame", row.names = c(NA, -5L))
> xx <- structure(list(a = 1:5, b = 11:15, c = structure(c(3L, 1L, 2L,
+ 1L, 3L), .Label = c("bar", "baz", "foo"), class = "factor")), .Names = c("a",
+ "b", "c"), class = "data.frame", row.names = c(NA, -5L))
> xx
a b c
1 1 11 foo
2 2 12 bar
3 3 13 baz
4 4 14 bar
5 5 15 foohttps://stackoverflow.com/questions/10849270
复制相似问题