将data.frame结构打印为字符

时间:2016-08-17 14:04:21

标签: r

我有一个看起来像这样的data.frame:

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

当我打印data.frame我(显然)得到这个输出:

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

是否有任何功能可以将data.frame打印为character string(或类似)?

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

我真的希望打印出"df <- data.frame(x = c(...), y = (...))"这样的内容,以便我可以复制输出并将其粘贴到stackoverflow问题(重现性)!

3 个答案:

答案 0 :(得分:3)

我最近不得不这样做。答案的核心确实是dput,但您希望capture.output将其转换为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\")"

如果你有同样的想法,那么你可以通过以下方式分配:

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

如果你真的需要分配箭头成为character的一部分,只需paste0即可。

答案 1 :(得分:0)

一个选项是使用:

  dput(df)

返回:

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

答案 2 :(得分:0)

我想我得到了一些东西!

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)

输出:

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

适合复制和粘贴到stackoverflow!