rclasssaver-s4

Easiest way to save an S4 class


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?


Solution

  • 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.