3

is there any package/command in R that reads a data.frame and then creates a command that can be used to create the exactly same data.frame without loading data, i.e., all data of the data.frame would have to be stored within the command?

e.g. if one has a data.frame like this:

mydata <- data.frame(col1=c(1,2),col2=c(3,4))

I just want to get the command such that reading "mydata" results in the command on the right hand side.

BR Fabian

Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
Fabian
  • 103
  • 6

2 Answers2

2

The dput function "Writes an ASCII text representation of an R object to a file or connection" and is as close to the right hand side as you would get. It actually contains more details about the structure of the object, as is seen below:

> dput(mydata)
structure(list(col1 = c(1, 2), col2 = c(3, 4)), .Names = c("col1", 
"col2"), row.names = c(NA, -2L), class = "data.frame")
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
1

You could also use enquote, which turns mydata back into an unevaluated call. It can then be evaluated with eval.

> ( e <- enquote(mydata) )
# quote(list(col1 = c(1, 2), col2 = c(3, 4)))
> eval(e)
#   col1 col2
# 1    1    3
# 2    2    4
> identical(eval(e), mydata)
# [1] TRUE
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245