emehex emehex - 3 months ago 10
R Question

Print data.frame structure as character

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)!

Answer

I just had to do this recently. The core of the answer is indeed dput, but you want capture.output to convert that to character:

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\")"

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.