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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With