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.
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.
This entry was posted on Tuesday, March 16th, 2010 at 10:52 pm and is filed under feature, r, stats. You can follow any comments to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.
© 2024.
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
Very helpful. Better than the usual “LOOPS ARE EVIL!!111111” instructions. Thanks!
The formatting of your code snippet is showing tags.
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
Thanks! so useful.
Thanks!…simple and effective …I m transitioning from python
This legit just solved a problem I was having all weekend. THANKS!
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)
}
Helped me too, thank you!