jf1 jf1 - 9 days ago 5
R Question

R autoload library when loading data file

Is there a possibility to define a library that gets loaded, when one reads in a saved object in an .rdata file. E.g.: after running:

library(data.table)
dt1 = data.table(a=1:10,b=letters[1:10])
save(dt1,file="dt.rdata")


dt1 is saved dt.rdata.

Alas when reading that file in to a pristine R session (e.g. by double clicking on the file in windows explorer) dt1 is available, but corresponding data.table commands can only be used after issuing an additional

library(data.table)


in the newly opened R session. Is there some way to define within the data file, that certain packages are to be loaded or some other commands are to be performed before/after reading in the respective file?

Answer

Save your data into a different workspace and add a function called .First which load the library.

.First <- function(){library(data.frame)}
Comments