使用脚本将dput加载到R中

时间:2015-08-24 14:42:30

标签: r reproducible-research

创建可重现的示例时,我经常要使用data.frame输出put()或类似内容:

my_data <- structure(list(pr_id = c("X1626", "X1689", "X1818", "X2044", 
"X1572"), t1 = c("PID", "WRC", "PID", "PID", "PID"), t2 = c("PRO", 
"DEC", "ECV", "PRO", "PRO"), t3 = c("REF", "", "ECV", "SMK", 
"REF"), t4 = c("ECV", "", "ECV", "SMK", "SMK"), t5 = c("SMK", 
"", "ECV", "ECV", "SMK"), t6 = c("SMK", "", "SMK", "", "TEA"), 
t7 = c("DEC", "", "DEC", "", "SMK"), t8 = c("", "", "REF", 
"", "SMK"), t9 = c("", "", "SMK", "", "TEA"), t10 = c("", 
"", "", "", "SMK"), t11 = c("", "", "", "", "SMK"), t12 = c("", 
"", "", "", "SMK"), t13 = c("", "", "", "", "SMK"), t14 = c("", 
"", "", "", "DEC")), .Names = c("pr_id", "t1", "t2", "t3", 
"t4", "t5", "t6", "t7", "t8", "t9", "t10", "t11", "t12", "t13", 
"t14"), row.names = c(NA, 5L), class = "data.frame")

但是,当我尝试加载数据时,它会要求我提供一个文件:

my_data_loaded <- dget(my_data)

Error in parse(file = file, keep.source = keep.source) : 
  'file' must be a character string or connection

如何轻松创建dput然后重新加载它以创建一个可重现的示例脚本?我想避免将其保存为文件,只需将整个内容作为脚本运行。

1 个答案:

答案 0 :(得分:2)

您的内容过于复杂 - 请参阅dput()的帮助和示例。

其输出意图复制到新的作业。这可以很简单:

R> ## let us create an object x
R> x <- c(a=1.23, b=42.3)
R> x
    a     b 
 1.23 42.30 
R> dput(x)
structure(c(1.23, 42.3), .Names = c("a", "b"))
R> 
R> ## now use the dput() output in an assignment
R> y <- structure(c(1.23, 42.3), .Names = c("a", "b"))
R>
R> ## and lo and behold:
R> identical(x, y)
[1] TRUE
R>