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.

6 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. 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

  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!

Leave a comment