Is there an R function that accepts an R object and returns code that can be run to generate that object?
Example
When passed the first 5 rows of the iris
dataframe
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
The function would generate the following string like so:
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)"
Then calling cat(string)
would print to console the exact code necessary to generate the object (in this case, a dataframe)
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)
Does such a function exist?