我有一些数据打印到控制台:
> head(mydata)
V1 V2 V3
1 29228 2005-01-01 00:00:00 12345
2 29228 2005-01-01 00:10:00 23456
3 29228 2005-01-01 00:20:00 34567
4 29228 2005-01-01 00:30:00 45678
我想与同事分享这些数据。如果我可以使用我的代码将数据放在r脚本中而不是共享一个单独的数据文件,那就太好了。
是否可以从字符串中读取此数据到R中,例如
> df <- read("
V1 V2 V3
1 29228 2005-01-01 00:00:00 12345
2 29228 2005-01-01 00:10:00 23456
3 29228 2005-01-01 00:20:00 34567
4 29228 2005-01-01 00:30:00 45678
")
答案 0 :(得分:1)
是的,虽然你有4列。
df <- read.table(text =
"V1 V2 V3 V4
1 29228 2005-01-01 00:00:00 12345
2 29228 2005-01-01 00:10:00 23456
3 29228 2005-01-01 00:20:00 34567
4 29228 2005-01-01 00:30:00 45678", header = TRUE)
你也可以
df = head(mydata)
答案 1 :(得分:1)
如果您要与其他R用户分享您的数据。最好使用dput命令。 例如:
df <- read.table(text =
"V1 V2 V3 V4
1 29228 2005-01-01 00:00:00 12345
2 29228 2005-01-01 00:10:00 23456
3 29228 2005-01-01 00:20:00 34567
4 29228 2005-01-01 00:30:00 45678", header = TRUE)
dput(df)
structure(list(V1 = c(29228L, 29228L, 29228L, 29228L), V2 = structure(c(1L,
1L, 1L, 1L), .Label = "2005-01-01", class = "factor"), V3 = structure(1:4, .Label = c("00:00:00",
"00:10:00", "00:20:00", "00:30:00"), class = "factor"), V4 = c(12345L,
23456L, 34567L, 45678L)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1",
"2", "3", "4"))
此输出将保留数据框的原始结构和格式,并采用更精简的形式。重新读取数据非常简单:
newdf<- structure(list(V1 = c(29228L, 29228L, 29228L, 29228L), V2 = structure(c(1L,
1L, 1L, 1L), .Label = "2005-01-01", class = "factor"), V3 = structure(1:4, .Label = c("00:00:00",
"00:10:00", "00:20:00", "00:30:00"), class = "factor"), V4 = c(12345L,
23456L, 34567L, 45678L)), .Names = c("V1", "V2", "V3", "V4"), class = "data.frame", row.names = c("1",
"2", "3", "4"))
这也是stackoverflow提供示例的首选方法!