11

Suppose an object is already defined in the workspace:

a <- round( rnorm(10) )

[1]  0 -1 -1 -1 -1  0  2  1  1  1

How can I programatically generate a command which creates a?

For example, I would like to use the a in my workspace to generate the following string codeToCreateA:

codeToCreateA <- "a <- c( 0, -1, -1, -1, -1,  0,  2,  1,  1,  1)"

I'm interested in the general case, in which a could be any class of object, including a vector, list, or data frame.

Bobby
  • 1,585
  • 3
  • 19
  • 42
  • 6
    You mean like `dput(a)`? Not sure what you mean by "as a string" – Rich Scriven Jul 18 '16 at 20:03
  • @Bobby I don't understand your question. do you want to generate a `numeric` vector ? –  Jul 18 '16 at 20:03
  • Just updated the question slightly. I hope that helps. Yes, `dput(a)` works in this case. Thanks! I just tried it on a data frame and got this result `structure(list(A = c("a", "a", "a", "b", "b"), B = 1:5), .Names = c("A", "B"), row.names = c(NA, -5L), class = c("data.table", "data.frame" ), .internal.selfref = )`. How can I create the data frame again from this code? – Bobby Jul 18 '16 at 20:13
  • @Bobby just assign the result of `dput(a)` to whatever variable name you want. – ytk Jul 18 '16 at 20:15
  • You can send it to file. `dput(a, file="a.R")`, then use `dget()` to get it. Something like `rm(a); assign("a", dget("a.R")); a` would do it. – Rich Scriven Jul 18 '16 at 20:16
  • Or just copy/paste. `a = structure(list(A = ....))` will create that data frame and assign it to the variable "a". The copy/pasteability is the [preferred method for sharing R objects on Stack Overflow](http://stackoverflow.com/a/5963610/903061). – Gregor Thomas Jul 18 '16 at 20:18
  • Yes, this was also part of my motivation for asking the question. `a <- structure(list(A = c("a", "a", "a", "b", "b"), B = 1:5), .Names = c("A", "B"), row.names = c(NA, -5L), class = c("data.table", "data.frame" ), .internal.selfref = )` works if I remove the last argument. Thanks! – Bobby Jul 18 '16 at 20:51

1 Answers1

7

dput(A) returns the structure of the object A. It can then be used to recreate A directly, or to share code for recreating a single object with others.

I've tested it on a vector, data frame, and list.

Here's an example for a data tablet (also of class data frame):

a <- structure(list(A = c("a", "a", "a", "b", "b"), B = 1:5), 
.Names = c("A", "B"), row.names = c(NA, -5L), 
class = c("data.table", "data.frame" ), 
.internal.selfref = <pointer: 0x22f5938>)

Note that the last argument needs to be removed before executing this code. i.e.

b <- structure(list(A = c("a", "a", "a", "b", "b"), B = 1:5), 
.Names = c("A", "B"), row.names = c(NA, -5L), 
class = c("data.table", "data.frame" ) )

The comments on the question above helped to prepare this answer.

Bobby
  • 1,585
  • 3
  • 19
  • 42