Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R function to convert object into code

Tags:

object

r

I am looking for a function in R that converts an object into code that can be used to create a replica of that object. Something like this:

> myObject=c(1, 2, 3)
> magicFunction(myObject)
[1] "c(1,2,3)"

I think this function exists, but I cannot find it. Would greatly appreciate your help.

like image 753
k-zar Avatar asked Nov 29 '16 04:11

k-zar


Video Answer


2 Answers

You can also use dput, as this retains the structure of the object as opposed to a character string representation of it.

From ?dput:

Writes an ASCII text representation of an R object to a file or connection, or uses one to recreate the object.

For example

myObject=c(1, 2, 3)

dput(myObject)
# c(1, 2, 3)


identical(myObject, dput(myObject))
# c(1, 2, 3)
# [1] TRUE

## whereas
identical(myObject, deparse(myObject))
# [1] FALSE
like image 193
SymbolixAU Avatar answered Oct 11 '22 20:10

SymbolixAU


We can use deparse

deparse(myObject)
#[1] "c(1, 2, 3)"
like image 43
akrun Avatar answered Oct 11 '22 20:10

akrun