作为字符串的复杂R对象的可逆集合结构
我希望能够将复杂的R对象转换为字符串,然后返回到原始对象 为简单起见,假设我有一个列表:作为字符串的复杂R对象的可逆集合结构,r,parsing,R,Parsing,我希望能够将复杂的R对象转换为字符串,然后返回到原始对象 为简单起见,假设我有一个列表: lt <- list(a=1:10,b=data.frame(a=10, b=1:5)) lt 但是,以下操作不起作用: x <- dput(lt) x x <- dput(lt,control="showAttributes") x eval(parse(x)) 下面给出了一个错误: dump(lt) 我能够根据以下要求使其工作: x我们有以下内容: lt <- list(
lt <- list(a=1:10,b=data.frame(a=10, b=1:5))
lt
但是,以下操作不起作用:
x <- dput(lt)
x
x <- dput(lt,control="showAttributes")
x
eval(parse(x))
下面给出了一个错误:
dump(lt)
我能够根据以下要求使其工作:
x我们有以下内容:
lt <- list(a=1:10,b=data.frame(a=10, b=1:5))
identical(eval(parse(text=deparse(lt))), lt)
## [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
f为什么要重建它?原始对象lt
仍然存在。
x <- capture.output(dput(lt))
x <- paste(x,collapse="",sep="")
x
dget(textConnection(x))
lt <- list(a=1:10,b=data.frame(a=10, b=1:5))
identical(eval(parse(text=deparse(lt))), lt)
## [1] TRUE
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
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