[R] change the names of all listed objects

Marc Schwartz marc_schwartz at comcast.net
Fri Aug 3 17:01:41 CEST 2007


On Fri, 2007-08-03 at 16:23 +0200, 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.
> Thank you very much for your help.
> Luca Laghi

Try this:

> ls()
character(0)


# Create the 7 objects
for (i in seq(7)) assign(letters[i], i)


> ls()
[1] "a" "b" "c" "d" "e" "f" "g" "i"


# Just get the objects we want
MyObj <- ls(pattern = "^[a-g]$")


> MyObj
[1] "a" "b" "c" "d" "e" "f" "g"


# Rename to new and delete old
for (i in MyObj)
{ 
  assign(paste(i, "1", sep = ""), get(i))      
  rm(list = i)
}


> ls()
[1] "a1"    "b1"    "c1"    "d1"    "e1"    "f1"    "g1"    "i"    
[9] "MyObj
 

See ?assign and ?get

You could encapsulate the above in a function, but need to be cautious
relative to environments and the old to new naming schema. 

HTH,

Marc Schwartz



More information about the R-help mailing list