Saturday, 21 January 2017

r - Automatically generate command to reproduce an object in the workspace





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.



Answer



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 = )


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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...