0

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?

stevec
  • 27,285
  • 13
  • 133
  • 181

1 Answers1

1

I think you are looking for dput.

For example, for 1st 5 rows of iris, you could do

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")

and now you could use the same code to recreate the object again.

Another example,

x <- c(3, 4, 1, 2)
dput(x)
#c(3, 4, 1, 2)
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
  • From R documentation: "dput {base} - Writes an ASCII text representation of an R object to a file or connection, or uses one to recreate the object.". I had not come across this function before. It is exactly what I am after! Thank you – stevec Jan 30 '19 at 18:33