To iterate over a list in R, you can use for loops or apply functions.
In this example,
numbers
with numeric elements.numbers <- c(10, 20, 30, 40, 50)
for (number in numbers) {
print(number)
}
[1] 10 [1] 20 [1] 30 [1] 40 [1] 50
In this example,
names
with character elements.lapply
function to apply a function to each element of the list.names <- c('Alice', 'Bob', 'Charlie', 'David')
upper_names <- lapply(names, toupper)
print(upper_names)
[[1]] [1] "ALICE" [[2]] [1] "BOB" [[3]] [1] "CHARLIE" [[4]] [1] "DAVID"
In this tutorial, we learned How to Iterate Over a List with Index in R language with well detailed examples.