R tip iterating over list

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

for (name in names(myList)) {
    print(name)
print(myList[[name]])
}

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

9 comments

  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.

    Ian

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

  3. The formatting of your code snippet is showing tags.

  4. 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.
    Tony

  5. Thanks! so useful.

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

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

  8. 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]]))
    }
    return(tt1)
    }

  9. Helped me too, thank you!

Leave a comment