0

The output of dput is usually much more complex than what a user would have typed to create the same object. I understand that this might be necessary to guarantee a 100% reproducibility (including for instance when different users use different default settings). However, it doesn't make examples as readable as they could be, and I often spend some time simplifying the output.

As an examples, consider:

dput(data.frame(a=1:10))
> structure(list(a = 1:10), .Names = "a", row.names = c(NA, -10L), class = "data.frame")

Isn't there an alternative to dput that would simply return data.frame(a=1:10) ?

nassimhddd
  • 8,340
  • 1
  • 29
  • 44
  • 2
    I don't understand why you worry about the complexity of `dput` output, since it is not intended to be read, but copied and pasted - in which case complexity doesn't really matter in my opinion. – talat Jul 28 '14 at 07:48
  • For a more readable representation, use `str(data.frame(a = 1:10))`. – tonytonov Jul 28 '14 at 07:58
  • 1
    @beginneR if it is meant to be embedded in a stackoverflow question, reproducible and readable is better than just reproducible. – nassimhddd Jul 28 '14 at 08:33
  • @tonytonov I should update my question title... I don't want any representation, but a command to recreate the object. Sorry I forgot to mention that. – nassimhddd Jul 28 '14 at 08:36
  • Did you study [How to make a great R reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)? In my opinion, this is a possible duplicate. – talat Jul 28 '14 at 08:55
  • @cafe876 `dput(data.frame(a=1:10), control = NULL)` may suit your needs; otherwise, if you need to "remember" how an object was created, use `expr <- "data.frame(a=1:10); df <- eval(parse(text=expr))"`, but this is a generally discouraged way to do things in R. – tonytonov Jul 28 '14 at 10:46

1 Answers1

3

Here is a partial implementation for data.frames (no row.names or other attributes):

dput2 <- function(x, ...) UseMethod("dput2")
dput2.data.frame <- function(x, ...) {
    fun <- function(nm) paste(nm, "=", 
            paste(capture.output(dput(x[[nm]], file = stdout())), collapse = ""))
    L <- lapply(names(x), fun)
    cat(paste("data.frame(", paste(unlist(L), collapse = ",\n"), ")"), "\n")
}

For example,

> dput2(BOD)
data.frame( Time = c(1, 2, 3, 4, 5, 7),
demand = c(8.3, 10.3, 19, 16, 15.6, 19.8) ) 

> dput2(anscombe)
data.frame( x1 = c(10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5),
x2 = c(10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5),
x3 = c(10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5),
x4 = c(8, 8, 8, 8, 8, 8, 8, 19, 8, 8, 8),
y1 = c(8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68),
y2 = c(9.14, 8.14, 8.74, 8.77, 9.26, 8.1, 6.13, 3.1, 9.13, 7.26, 4.74),
y3 = c(7.46, 6.77, 12.74, 7.11, 7.81, 8.84, 6.08, 5.39, 8.15, 6.42, 5.73),
y4 = c(6.58, 5.76, 7.71, 8.84, 8.47, 7.04, 5.25, 12.5, 5.56, 7.91, 6.89) ) 
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341