jaySf jaySf - 3 years ago 187
R Question

Save individual selection of global environment to Rdata

When we want so save the global evironment to disk we use

save(list = ls(.GlobalEnv), file = "data.Rdata")
- okay.

When one specific object should be saved we use
save(data.1, file = "data.Rdata")
- bien.

But what is to do when from an environment
data.1, data.2, data.3
only
data.1
and
data.2
should be saved?

Neither
save(c(data.1, data.2), file = "data.Rdata")
nor
save(list = ls(data.1, data.2), file = "data.Rdata")
is working.

Answer Source

There are many ways ... perhaps not countless, 'cause we "can" count them, but ...

save(data.1, data.2, file = "data.Rdata")

This saves just two objects, named, within the rda file.

For the latter form, you were close when you gave the example of

save(list = ls(.GlobalEnv), file = "data.Rdata")

Note that ls(.GlobalEnv) returns a character vector, which is what the man page for save says it needs. That should trigger the realization that this vector can be derived from ls() or from anything else that creates a vector, including manually:

save(list=c("data.1", "data.2"), file = "data.Rdata")

This latter technique is very handy when saving variables programmatically, where you may choose to not hard-code variable names (or have a variable number of them).

When trying to figure this out, it might be informative to try the nested commands first before putting them within a save. For instance, c(data.1, data.2) just concatenates the data objects, which may be useful or not; regardless, though, save expects an object in the ... to be a symbol or object ... but a derived object like within c() won't work.

Similarly, ls(data.1) should have given you a reply along the lines of as.environment(pos) (from pit-roads.R#157) : invalid 'pos' argument, indicating that your expection of the ls function is a bit amyss.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download