0

While there are functions for saving data as a separate CSV file (write.table) or as an R-data file (save, saveRDS), I have not found a way to store or print a data frame as R code that recreates this data frame.

Background of my question is that I want to include data with a script (instead of storing it in a separate file), and am thus looking for a way to generate the specific code provided the data frame already exists. I could hack on with sed or other external tools, but I wonder whether someone knows of a built-in method in R.

cdalitz
  • 1,019
  • 1
  • 6
  • 7
  • 1
    See `help("dput")` (as you would know if you had read the [top-voted R question](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)). – Roland Jul 30 '20 at 10:42
  • Great, that does the trick! Before posting,I had spent some time searching for an answer but did not search for "reproducible example". – cdalitz Jul 30 '20 at 10:53
  • You could also just have read the [tag:r] tag [info](https://stackoverflow.com/tags/r/info). ;) – Roland Jul 30 '20 at 10:56
  • Okay, I understood: shame on me! Nevertheless thanks for taking the trouble to answer. – cdalitz Jul 30 '20 at 10:58

1 Answers1

1

Try with "dput" like so:

dput(cars)
# Returns:
structure(list(speed = c(4, 4, 7, 7, 8, 9, 10, 10, 10, 11, 11, 
12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 16, 
16, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 20, 20, 20, 20, 20, 
22, 23, 24, 24, 24, 24, 25), dist = c(2, 10, 4, 22, 16, 10, 18, 
26, 34, 17, 28, 14, 20, 24, 28, 26, 34, 34, 46, 26, 36, 60, 80, 
20, 26, 54, 32, 40, 32, 40, 50, 42, 56, 76, 84, 36, 46, 68, 32, 
48, 52, 56, 64, 66, 54, 70, 92, 93, 120, 85)), class = "data.frame", 
row.names = c(NA, -50L))
Repmat
  • 690
  • 6
  • 19