【问题标题】:R function that accepts an object and returns the code necessary to generate that object in the R interpreter [closed]R函数,它接受一个对象并返回在R解释器中生成该对象所需的代码[关闭]
【发布时间】:2019-01-30 07:02:13
【问题描述】:

是否有一个 R 函数可以接受 R 对象并返回可以运行以生成该对象的代码?

例子

当传递iris 数据帧的前 5 行时

iris
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa

该函数将生成如下字符串:

string <- "data.frame(\"Sepal.Length\"=as.numeric(c(5.1, 4.9, 4.7, 4.6, 5.0)), \"Sepal.Width\"=as.numeric(c(3.5, 3.0, 3.2, 3.1, 3.6)), \"Petal.Length\"=as.numeric(c(1.4, 1.4, 1.3, 1.5, 1.4)), \"Petal.Width\"=as.numeric(c(0.2, 0.2, 0.2, 0.2, 0.2)), \"Species\"=as.factor(c(\"setosa\", \"setosa\", \"setosa\", \"setosa\", \"setosa\")), stringsAsFactors = FALSE)"

然后调用cat(string) 将打印到控制台生成对象(在本例中为数据帧)所需的确切代码

data.frame("Sepal.Length"=as.numeric(c(5.1, 4.9, 4.7, 4.6, 5.0)), "Sepal.Width"=as.numeric(c(3.5, 3.0, 3.2, 3.1, 3.6)), "Petal.Length"=as.numeric(c(1.4, 1.4, 1.3, 1.5, 1.4)), "Petal.Width"=as.numeric(c(0.2, 0.2, 0.2, 0.2, 0.2)), "Species"=as.factor(c("setosa", "setosa", "setosa", "setosa", "setosa")), stringsAsFactors = FALSE)

这样的功能存在吗?

【问题讨论】:

标签: r


【解决方案1】:

我认为您正在寻找dput

例如,对于iris 的第 5 行,您可以这样做

dput(iris[1:5,])

#structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5), Sepal.Width = c(3.5, 
#3, 3.2, 3.1, 3.6), Petal.Length = c(1.4, 1.4, 1.3, 1.5, 1.4), 
#    Petal.Width = c(0.2, 0.2, 0.2, 0.2, 0.2), Species = structure(c(1L, 
#    1L, 1L, 1L, 1L), .Label = c("setosa", "versicolor", "virginica"
#    ), class = "factor")), .Names = c("Sepal.Length", "Sepal.Width", 
#"Petal.Length", "Petal.Width", "Species"), row.names = c(NA, 
#5L), class = "data.frame")

现在您可以使用相同的代码再次重新创建对象。

另一个例子,

x <- c(3, 4, 1, 2)
dput(x)
#c(3, 4, 1, 2)

【讨论】:

  • 来自 R 文档:“dput {base} - 将 R 对象的 ASCII 文本表示写入文件或连接,或使用一个来重新创建对象。”。我以前没有遇到过这个功能。这正是我所追求的!谢谢
猜你喜欢
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
  • 1970-01-01
  • 2012-02-14
相关资源
最近更新 更多