Reputation: 24596
I have some data that I printed out to the console:
> 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
I want to share this data with a colleague. It would be great if I could have the data in an r script with my code rather than having to share a separate data file.
Is it possible to read this data in to R from a string, e.g.
> 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
")
Upvotes: 1
Views: 62
Reputation: 24079
If you what to share your data with another R user. It is better to use the dput command. For example:
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"))
This output will preserve the original structure and formatting of the dataframe and with a more condensed form. To read the data back in is just a simple:
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"))
This is also the preferred method of providing examples here at stackoverflow!
Upvotes: 1
Reputation: 4024
Yes, although you have 4 columns.
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)
you could also do
df = head(mydata)
Upvotes: 1