Loop directly over the nyc list (loop version 1). Define a looping index and do subsetting using double brackets (loop version 2).
nyc <- list(pop = 8405837,
boroughs = c("Manhattan", "Bronx", "Brooklyn", "Queens", "Staten Island"),
capital = FALSE)
Loop version 1
for (i in nyc){
print(i)
}
## [1] 8405837
## [1] "Manhattan" "Bronx" "Brooklyn" "Queens"
## [5] "Staten Island"
## [1] FALSE
Loop version 2
for (i in 1:length(nyc)){
print(nyc[[i]])
}
## [1] 8405837
## [1] "Manhattan" "Bronx" "Brooklyn" "Queens"
## [5] "Staten Island"
## [1] FALSE
Notice that you need double square brackets - [[ ]] - to select the list elements in loop version 2.