R列表到字符串表示

时间:2016-02-15 16:00:33

标签: r

我想得到一个列表的字符串表示,可用于重新创建具有相同值的列表。

我正在搜索的内容类似于Python repr()函数。

model = list(name='ugarch', spec=list(garchOrder = c(1, 1)))

str = str_repr(model)

# str should be equal to "list(name='ugarch', spec=list(garchOrder = c(1, 1)))"

有没有办法在R中执行此操作?

1 个答案:

答案 0 :(得分:0)

dput函数几乎执行您想要的操作:它尝试将对象解压缩为ASCII文本表示形式。但是,它不适合编程:字符串表示写入stdout或文件(默认是写入控制台),实际输出只是输入的不可见副本:

dput(list(x = 1))
## structure(list(x = 1), .Names = "x")
y <- dput(list(x = 1))
## structure(list(x = 1), .Names = "x")
y
## $x
## [1] 1

class(y)
## [1] "list"

但是,您可以使用dputcapture.output编写具有所需行为的函数:

repr <- function(x) {
    y <- capture.output(dput(x))
    paste(y, collapse = '')
}

z <- repr(list(x = 1))
z
## [1] "structure(list(x = 1), .Names = \"x\")"
class(z)
## [1] "character"
相关问题