How to for-Loop Over List Elements in R (Example Code)

In this article, I’ll illustrate how to loop over list elements in the R programming language.

Example Data

list_object <- list(1:7,                          # Exemplifying list in R
                "hahahaha",
                letters[10:5],
                "lala", "lolo")
list_object                                       # Returning list to console
# [[1]]
# [1] 1 2 3 4 5 6 7
# 
# [[2]]
# [1] "hahahaha"
# 
# [[3]]
# [1] "j" "i" "h" "g" "f" "e"
# 
# [[4]]
# [1] "lala"
# 
# [[5]]
# [1] "lolo"

Example: Looping Through List Elements Using for-Loop

for(i in 1:length(list_object)) {                 # Starting the for-loop
  
  list_object[[i]] <- rep(list_object[[i]], 3)    # Modifying list
}
list_object                                       # Returning new list to console
# [[1]]
# [1] 1 2 3 4 5 6 7 1 2 3 4 5 6 7 1 2 3 4 5 6 7
# 
# [[2]]
# [1] "hahahaha" "hahahaha" "hahahaha"
# 
# [[3]]
# [1] "j" "i" "h" "g" "f" "e" "j" "i" "h" "g" "f" "e" "j" "i" "h" "g" "f" "e"
# 
# [[4]]
# [1] "lala" "lala" "lala"
# 
# [[5]]
# [1] "lolo" "lolo" "lolo"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top