Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to save an S4 class

Tags:

class

r

save

s4

Probably the most basic question on S4 classes imaginable here.

What is the simplest way to save an S4 class you have defined so that you can reuse it elsewhere. I have a project where I'm taking a number of very large datasets and compiling summary information from them into small S4 objects. Since I'll therefore be switching R sessions to create the summary object for each dataset, it'd be good to be able to load in the definition of the class from a saved object (or have it load automatically) rather than having to include the long definition of the object at the top of each script (which I assume is bad practice anyway because the code defining the object might become inconsistent).

So what's the syntax along the lines of saveclass("myClass"), loadclass("myclass") or am I just thinking about this in the wrong way?

like image 629
Jon M Avatar asked Sep 30 '22 21:09

Jon M


1 Answers

setClass("track", representation(x="numeric", y="numeric"))
x <- new("track", x=1:4, y=5:8)

save as binary

fn <- tempfile()
save(x, ascii=FALSE, file=fn)
rm(x)
load(fn)
x

save as ASCII

save(x, ascii=TRUE, file=fn)

ASCII text representation from which to regenerate the data

dput(x, file=fn)
y <- dget(fn) 

The original source can be found here.

like image 200
Hack-R Avatar answered Oct 03 '22 02:10

Hack-R