Tuesday, 11 July 2017

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

Answer


Answer






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

casting - Why wasn&#39;t Tobey Maguire in The Amazing Spider-Man? - Movies &amp; TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...