[R] change the names of all listed objects

Duncan Murdoch murdoch at stats.uwo.ca
Fri Aug 3 17:17:33 CEST 2007


On 8/3/2007 10:23 AM, Luca Laghi wrote:
> Dear list members,
> I have created seven objects, from a to g, so that ls() gives me
> [1] "a" "b" "c" "d" "e" "f" "g"
> 
> how can I automatically change their names in
> 
> "a1" "b1" "c1" "d1" "e1" "f1" "g1"
> 
> It seems simple, ut it is driving me mad.

R doesn't have a "rename" operation, so you need to copy the objects and 
then delete the original.  For example:

# create a vector of the names of your objects
namelist <- letters[1:7]

for (i in seq_along(namelist)) {
   oldname <- namelist[i]

   # compute a new name from the old one
   newname <- paste(oldname, "1", sep="")

   # create a variable with the new name
   assign(newname, get(oldname))

   # delete the old object
   rm(list=oldname)
}


The code above should work in simple cases where you run it in the 
console and it works on objects in the global workspace.  If you want to 
write a function to do this things get more complicated, because you 
want to make the assignment in the same place the function found the 
original.

There are quicker ways (using mget() and apply()), but they'd really 
just be doing the same as the above in a less clear way.

Duncan Murdoch



More information about the R-help mailing list