R tip iterating over list

To iterate over a list by key, value pair, do this:

for (name in names(myList)) {
    print(name)<br />
    print(myList[[name]])<br />

Note the double [[]] so you get just the value, not the pair.


  1. Thanks for that snippet!

    I was able to write a script that allows me to list the levels associated with each of the named variables.


  2. Very helpful. Better than the usual “LOOPS ARE EVIL!!111111” instructions. Thanks!

  3. Hey man,
    I know this post is pretty old, but I just wanted to say “Thanks.” It just helped me shorten a chunk of code from hundreds of lines down to ten.

  4. Thanks! so useful.

  5. Thanks!…simple and effective …I m transitioning from python

  6. This legit just solved a problem I was having all weekend. THANKS!

  7. Thanks for the tip on iterating over a list. I have the following function to iterate over a list, which is a river network formed by various segments, but the result is always one segment, I’m missing something in the code, any suggestions?

    my code:
    test.func = function(x){
    for (i in 1:length(x)) {
    tt[[i]] <- x[i]; tt[[i]] = Line(tt[[i]]); tt[[i]] = Lines(list(tt[[i]] ), 'i')
    tt1 = SpatialLines(list(tt[[i]]))

  8. Helped me too, thank you!

Leave your reply to Matt