[R] loading saved files with objects in same names

Martin Maechler maechler at stat.math.ethz.ch
Fri Aug 22 11:46:52 CEST 2014


> On 20/08/2014, 8:58 AM, Barry Rowlingson wrote:
> > On Tue, Aug 19, 2014 at 1:30 AM, Jinsong Zhao <jszhao at yeah.net> wrote:
> >> Hi there,
> >>
> >> I have several saved data files (e.g., A.RData, B.RData and C.RData). In
> >> each file, there are some objects with same names but different
> >> contents. Now, I need to compare those objects through plotting.
> >> However, I can't find a way to load them into a workspace. The only
> >> thing I can do is to rename them and then save and load again.
> >>
> >> Is there a convenient to load those objects?
> >>
> >> Thanks a lot in advance.
> > 
> > The technique of loading into an environment already mentioned can be
> > cleaned up and put into a function.
> > 
> > First lets save a thing called "x" into two files with different values:
> > 
> >  > x="first"
> >  > save(x,file="f.RData"))
> >  > x="second"
> >  > save(x,file="s.RData")
> > 
> > This little function wraps the loading:
> > 
> >  > getFrom=function(file, name){e=new.env();load(file,env=e);e[[name]]}
> > 
> > So now I can get 'x' from the first file - the value is returned from
> > `getFrom` so I can assign it to anything:
> > 
> >  > x1 =  getFrom("f.RData","x")
> >  > x1
> > [1] "first"
> >  > x2 = getFrom("s.RData","x")
> >  > x2
> > [1] "second"
> > 
> > And I can even loop over RData files and read in all the `x`s into a vector:
> > 
> >  > sapply(c("f.RData","s.RData"),function(f){getFrom(f,"x")})
> >   f.RData  s.RData
> >   "first" "second"
> > 
> > (on second thoughts, possibly 'loadFrom' is a better name)

> That's a nice little function.  You could also have lsFrom, that lists
> the objects stored in the file, along the same lines:

> lsFrom <- function(file, all.names = FALSE, pattern) {
>   e <- new.env()
>   load(file, envir = e)
>   ls(e, all.names = all.names, pattern = pattern)
> }

> Duncan Murdoch

Note that the solution of simply using 

     attach("f.RData")

makes the use of  ls()  very natural, 
and for Rstudio and similar gui users, even automatically part of
their GUI.

Martin Maechler



More information about the R-help mailing list