Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically generate command to reproduce an object in the workspace [duplicate]

Tags:

r

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.

like image 622
Bobby Avatar asked Jul 18 '16 20:07

Bobby


1 Answers

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.

like image 172
Bobby Avatar answered Oct 08 '22 15:10

Bobby