0

When creating a reproducible example I often want to output a data.frame or similar using put():

my_data <- structure(list(pr_id = c("X1626", "X1689", "X1818", "X2044", 
"X1572"), t1 = c("PID", "WRC", "PID", "PID", "PID"), t2 = c("PRO", 
"DEC", "ECV", "PRO", "PRO"), t3 = c("REF", "", "ECV", "SMK", 
"REF"), t4 = c("ECV", "", "ECV", "SMK", "SMK"), t5 = c("SMK", 
"", "ECV", "ECV", "SMK"), t6 = c("SMK", "", "SMK", "", "TEA"), 
t7 = c("DEC", "", "DEC", "", "SMK"), t8 = c("", "", "REF", 
"", "SMK"), t9 = c("", "", "SMK", "", "TEA"), t10 = c("", 
"", "", "", "SMK"), t11 = c("", "", "", "", "SMK"), t12 = c("", 
"", "", "", "SMK"), t13 = c("", "", "", "", "SMK"), t14 = c("", 
"", "", "", "DEC")), .Names = c("pr_id", "t1", "t2", "t3", 
"t4", "t5", "t6", "t7", "t8", "t9", "t10", "t11", "t12", "t13", 
"t14"), row.names = c(NA, 5L), class = "data.frame")

However, when I try to load the data it asks me for a file:

my_data_loaded <- dget(my_data)

Error in parse(file = file, keep.source = keep.source) : 
  'file' must be a character string or connection

How can I easily create a dput and then load it back in again in order to create a script that is a reproducible example? I want to avoid saving it as a file, and simply run the entire thing as a script.

histelheim
  • 4,938
  • 6
  • 33
  • 63
  • 2
    `my_data` is already the actual object you're trying to load. If you want to save something as a file and load it (not as an active R object), you can do `save(my_data, "my_data.rdata")` and `load("my_data.rdata")` – Señor O Aug 24 '15 at 14:45
  • 2
    ...or, to use `dput` and `dget` one would have to follow the documentation and actually use `dput` to send the object to a file, not an object in your workspace. – joran Aug 24 '15 at 14:49

1 Answers1

2

You are over-complicating things -- see the help and example for dput().

Its output is meant to be copied over to a new assignment. This can be this simple:

R> ## let us create an object x
R> x <- c(a=1.23, b=42.3)
R> x
    a     b 
 1.23 42.30 
R> dput(x)
structure(c(1.23, 42.3), .Names = c("a", "b"))
R> 
R> ## now use the dput() output in an assignment
R> y <- structure(c(1.23, 42.3), .Names = c("a", "b"))
R>
R> ## and lo and behold:
R> identical(x, y)
[1] TRUE
R> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725