Noor Noor - 3 years ago 135
R Question

How to make a for loop for each vector in list

I have a list l, contains four vectors, each vector contains a number of elements, the vectors are not the same length.

l<- list(2:4,3:5,4:7,5:7)

for ( i in length(l)){

print(l)
}

[[1]]
[1] 2 3 4

[[2]]
[1] 3 4 5

[[3]]
[1] 4 5 6 7

[[4]]
[1] 5 6 7


I would like to add value 2 to all the elements of each vector in the list using for loop.

Maybe we need (two for loops) The external will be for the list and the internal will be for each vector of the list, I would like to obtain the following result :

[[1]]
[1] 4 5 6

[[2]]
[1] 5 6 7

[[3]]
[1] 6 7 8 9

[[4]]
[1] 7 8 9


Please note that: the original list contains 389 vectors, each vector contains not less than 45 elements.

Answer Source

A much faster and cleaner way is to not use a loop. Here, we are mapping each vector .x in l to .x + 2.

purrr::map(l, ~.x + 2)
# [[1]]
# [1] 4 5 6
# 
# [[2]]
# [1] 5 6 7
# 
# [[3]]
# [1] 6 7 8 9
# 
# [[4]]
# [1] 7 8 9

If you really need the loop version, just loop through the indexes of l and add 2 to each vector.

for (i in seq_along(l)) {
  l[[i]] <- l[[i]] + 2
}
print(l)
# [[1]]
# [1] 4 5 6
# 
# [[2]]
# [1] 5 6 7
# 
# [[3]]
# [1] 6 7 8 9
# 
# [[4]]
# [1] 7 8 9
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download