【发布时间】: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)
这样的功能存在吗?
【问题讨论】:
-
您可以使用
dput。它会给你准确的代码来创建传递的对象。dput(iris[1:5, ])
标签: r