How to iterate through list elements in R language?

In R language, you can use a for loop or the lapply function to iterate over list elements.

  1. Iterate through the elements of a list using a for loop.
mylist <- list(1, 2, 3, 4, 5)
for (i in seq_along(mylist)) {
  print(mylist[[i]])
}
  1. Traverse list elements using the lapply function.
mylist <- list(1, 2, 3, 4, 5)
lapply(mylist, function(x) {
  print(x)
})

Both methods will print out the elements of the list one by one.

bannerAds