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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.