获取分配给变量的输出数据



当我尝试将dput赋值给object时,它赋值并打印下面的值。这不应该发生。它应该传递给对象

get_ls <- dput(head(iris))
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4), 
Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4, 
1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2, 
0.2, 0.2, 0.4), Species = structure(c(1L, 1L, 1L, 1L, 1L, 
1L), .Label = c("setosa", "versicolor", "virginica"), class = "factor")), row.names = c(NA, 
6L), class = "data.frame")

预期输出

get_ls <- dput(head(iris))
get_ls
structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4), 
Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4, 
1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2, 
0.2, 0.2, 0.4), Species = structure(c(1L, 1L, 1L, 1L, 1L, 
1L), .Label = c("setosa", "versicolor", "virginica"), class = "factor")), row.names = c(NA, 
6L), class = "data.frame")

您可以编写一个新函数来提取dput()打印的调用

dput.call <- function(x) {
parse(text = capture.output(dput(x)))[[1]]
}
get_ls <- dput.call(head(iris))
get_ls
# structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4), 
#     Sepal.Width = c(3.5, 3, 3.2, 3.1, 3.6, 3.9), Petal.Length = c(1.4, 
#         1.4, 1.3, 1.5, 1.4, 1.7), Petal.Width = c(0.2, 0.2, 0.2, 
#         0.2, 0.2, 0.4), Species = structure(c(1L, 1L, 1L, 1L, 
#         1L, 1L), .Label = c("setosa", "versicolor", "virginica"), 
#         class = "factor")), row.names = c(NA, 6L), class = "data.frame")
class(get_ls)
# [1] "call"

这是你想要的吗?

con <- file() # new connect
dput(mtcars, con) # dump the dput in the connection
readLines(con) # read it as a vector