Reputation: 10548
I have a data.frame that looks like this:
df <- data.frame(
y = c(0.348, 0.099, 0.041, 0.022, 0.015, 0.010, 0.007, 0.005, 0.004, 0.003),
x = c(458, 648, 694, 724, 756, 790, 818, 836, 848, 876))
When I print the data.frame
I (obviously) get this output:
df
# y x
# 1 0.348 458
# 2 0.099 648
# 3 0.041 694
# 4 0.022 724
# 5 0.015 756
# 6 0.010 790
# 7 0.007 818
# 8 0.005 836
# 9 0.004 848
# 10 0.003 876
Is there any function where I can print the data.frame
as a character string
(or similar)?
magic_function(df)
# output
"df <- data.frame(
y = c(0.348, 0.099, 0.041, 0.022, 0.015, 0.010, 0.007, 0.005, 0.004, 0.003),
x = c(458, 648, 694, 724, 756, 790, 818, 836, 848, 876))"
I literally want to print out something like "df <- data.frame(x = c(...), y = (...))"
so that I can copy the output and paste it to a stackoverflow question (for reproducibility)!
Upvotes: 2
Views: 1115
Reputation: 34743
I just had to do this recently. deparse
will do the trick, and you can paste
the multi-line output into a single string with collapse
:
df.as.char <- paste(deparse(df), collapse = "")
df.as.char
# [1] "structure(list(y = c(0.348, 0.099, 0.041, 0.022, 0.015, 0.01, 0.007, 0.005, 0.004, 0.003), x = c(458, 648, 694, 724, 756, 790, 818, 836, 848, 876)), .Names = c(\"y\", \"x\"), row.names = c(NA, -10L), class = \"data.frame\")"
Depending on the size of your object, you might consider using the width.cutoff
argument to deparse
(which will reduce the number of lines created by deparse
).
If you've got the same thing in mind that I did, then you can assign this through:
df.from.char <- eval(parse(text = df.as.char))
df.from.char
# y x
# 1 0.348 458
# 2 0.099 648
# 3 0.041 694
# 4 0.022 724
# 5 0.015 756
# 6 0.010 790
# 7 0.007 818
# 8 0.005 836
# 9 0.004 848
# 10 0.003 876
identical(df.from.char, df)
# [1] TRUE
And if you really need the assignment arrow to be part of the character
, just paste0
that in.
Upvotes: 4
Reputation: 10548
I think I got something!
df4so <- function(df) {
# collapse dput
# shout out to KonradRudolph, Roland and MichaelChirico
a <- paste(capture.output(dput(df)), collapse = "")
# remove structure junk
b <- gsub("structure\\(list\\(", "", a)
# remove everything after names
c <- gsub("\\.Names\\s.*","",b)
# remove trailing whitespace
d <- gsub("\\,\\s+$", "", c)
# put it all together
e <- paste0('df <- data.frame(', d)
# return
print(e)
}
df4so(df)
Output:
[1] "df <- data.frame(y = c(0.348, 0.099, 0.041, 0.022, 0.015, 0.01, 0.007, 0.005, 0.004, 0.003), x = c(458, 648, 694, 724, 756, 790, 818, 836, 848, 876))"
Suitable for copying and pasting to stackoverflow!
Upvotes: 0
Reputation: 1869
one option is to use:
dput(df)
returns:
structure(list(y = c(0.348, 0.099, 0.041, 0.022, 0.015, 0.01,
0.007, 0.005, 0.004, 0.003), x = c(458, 648, 694, 724, 756, 790,
818, 836, 848, 876)), .Names = c("y", "x"), row.names = c(NA,
-10L), class = "data.frame")
Upvotes: 0