Skip to content

Instantly share code, notes, and snippets.

@jlmelville
Last active December 30, 2015 04:50
Show Gist options
  • Save jlmelville/0856c2523b6dc3c84ff3 to your computer and use it in GitHub Desktop.
Save jlmelville/0856c2523b6dc3c84ff3 to your computer and use it in GitHub Desktop.
Iterating over a list in R
# a simple function to create a list of lists:
list_of_lists <- function(...) {
list(...)
}
my_lol <- list_of_lists(list(cleesh = "krill"), list(nitfol = "rezrov"))
# want to print out "krill" and "rezrov"
# various suggestions for iterating over a list:
for (name in names(my_lol)) {
message(my_lol[[name]][[1]])
}
# Nothing happens, because:
names(my_lol) # NULL
for (i in 1:length(my_lol)) {
message(my_lol[[i]])
}
# this works - hurrah!
# but what if the list is empty?
my_empty_lol <- list_of_lists()
for (i in 1:length(my_empty_lol)) {
message(my_empty_lol[[i]])
}
# Error in my_empty_lol[[i]] : subscript out of bounds
# Boo!
# How about:
for (i in seq_along(my_lol)) {
message(my_lol[[i]])
}
# Works...
for (i in seq_along(my_empty_lol)) {
message(my_empty_lol[[i]])
}
# ... also works (in that it prints out nothing and doesn't give an error)
# Moral of the story: use seq_along
@jlmelville
Copy link
Author

Yes, one should avoid iterating with for loops in R lest one seem gauche or improper. But sometimes it's just easier to. With that in mind, there's a lot of advice out there on how to do it. I found that not all of that advice covered the cases where:

  • The list might be empty.
  • The list might not have names defined.

Using seq_along seems like the best bet.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment