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
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 LaghiTry 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
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