2

Possible Duplicate:
How to name variables on the fly in R?

I have 10 objects of type list named: list1, list2, ..., list10. And I wanted to use the output from my function FUN to replace the first index of these list variables through a for loop like this:

for (i in 1:10){
  eval(parse(test=(paste("list",i,sep=""))))[[1]] <- FUN()
}

but this does not work. I also used lapply in this way and again it is wrong:

 lapply(eval(parse(text=(paste("list",i,sep=""))))[[1]], FUN)

Any opinion would be appreciated.

Community
  • 1
  • 1
hora
  • 845
  • 5
  • 14
  • 25
  • 5
    See ?get and ?assign for future reference. You'd probably be better off saving your objects as a formal list and using lapply() though. – Brandon Bertelsen Nov 07 '12 at 15:13

2 Answers2

4

This is FAQ 7.21. The most important part of that FAQ is the last part that says not to do it that way, but to put everything into a list and operate on the list.

You can put your objects into a list using code like:

mylists <- lapply( 1:10, function(i) get( paste0('list',i) ) )

Then you can do the replacement with code like:

mylists <- lapply( mylists, function(x) { x[[1]] <- FUN()
  x} )

Now if you want to save all the lists, or delete all the lists, you just have a single object that you need to work with instead of looping through the names again. If you want to do something else to each list then you just use lapply or sapply on the overall list in a single easy step without worrying about the loop. You can name the elements of the list to match the original names if you want and access them that way as well. Keeping everything of interest in a single list will also make your code safer, much less likely to accidentilly overwrite or delete another object.

Greg Snow
  • 48,497
  • 6
  • 83
  • 110
  • also: http://stackoverflow.com/questions/6145118/with-r-loop-over-data-frames-and-assign-appropriate-names-to-objects-created-i , http://stackoverflow.com/questions/3094111/r-turning-list-items-into-objects ... basically, now that you know what to look for, you can search StackOverflow with keywords like `[r] get assign paste 7.21` ... – Ben Bolker Nov 07 '12 at 19:37
2

You probably want something like

for (i in 1:10) {
  nam <- paste0("list", i)  ## built the name of the object
  tmp <- get(nam)           ## fetch the list by name, store in tmp
  tmp[[1]] <- FUN()         ## alter 1st component of tmp using FUN()
  assign(nam, value = tmp)  ## assign tmp back to the current list
}

as the loop.

Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
  • 2
    @hora Welcome to [so] and glad you found the answer useful. If you are happy with an answer provided to a question of yours, please consider accepting it. to do so, click the big tick mark next to the answer you wish to accept. See the [ask] section of the FAQ for more details on the process and why it is useful for [so] that you do so. – Gavin Simpson Nov 07 '12 at 15:32