【问题标题】:Reversibly collection structure of complex R object as a string复杂R对象作为字符串的可逆集合结构
【发布时间】:2014-04-29 15:23:59
【问题描述】:

我希望能够将复杂的 R 对象转换为字符串,然后再转换回原始对象。

为简单起见,假设我有一个列表:

lt <- list(a=1:10,b=data.frame(a=10, b=1:5))
lt

如果我想在屏幕上看到这个,我会执行以下操作:

dput(lt)

但是,以下方法不起作用:

x <- dput(lt)
x
x <- dput(lt,control="showAttributes")
x

因为 x == lt 的值。

根据之前的尝试,我尝试了几件事:例如deparse

x <- deparse(lt)
x

有效,但反转无效:

eval(parse(x))

以下给出错误:

dump(lt)

根据this advice,我可以让它工作:

x <- capture.output(dput(lt))
x <- paste(x,collapse="",sep="")
x

dget(textConnection(x))

但是,我想知道第一种方法有什么问题(使用 eval(parse(x)))。 非常感谢任何帮助!

【问题讨论】:

  • 为什么要重构它?原始对象lt 仍然存在。

标签: r parsing


【解决方案1】:

我们有以下内容:

lt <- list(a=1:10,b=data.frame(a=10, b=1:5))
identical(eval(parse(text=deparse(lt))), lt)
## [1] TRUE

注意parse() 中的text 参数设置。

此外,

identical(eval(dput(lt)), lt)
## structure(list(a = 1:10, b = structure(list(a = c(10, 10, 10, 
## 10, 10), b = 1:5), .Names = c("a", "b"), row.names = c(NA, -5L
## ), class = "data.frame")), .Names = c("a", "b"))
## [1] TRUE

在这里,调用dput() 的副作用是将其值打印到控制台。要禁用此功能,您可以例如将其输出重定向到/dev/null(不过,这在 Windows 上不起作用)。

这绝对是使用dump的最不雅的恕我直言方式:

f <- textConnection(NULL, open="w")
dump("lt", f)
val <- textConnectionValue(f)
close(f)
print(val)
## [1] "lt <-"                                                             
## [2] "structure(list(a = 1:10, b = structure(list(a = c(10, 10, 10, "    
## [3] "10, 10), b = 1:5), .Names = c(\"a\", \"b\"), row.names = c(NA, -5L"
## [4] "), class = \"data.frame\")), .Names = c(\"a\", \"b\"))"            
lt2 <- lt # copy
eval(parse(text=val)) # re-creates lt
identical(lt2, lt)
## [1] TRUE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 2014-04-25
    • 1970-01-01
    • 2021-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多