elliot
elliot

Reputation: 1944

How to use lapply with two different lists in a way that is similar to a for loop?

I'd like to iterate over two lists in R and apply a function using lapply or purrr's map function. This code shows exactly what I'd like to do using a for loop.

nums_a <- list(c(1,2,3),c(5,6,7))
nums_b <- list(c(13,42,63),c(75,76,27))

nums_c <- list(NULL)
for (i in seq_along(nums_a)) {
 nums_c[[i]] <- nums_a[[i]]+nums_b[[i]]
}
nums_c
[[1]]
[1] 14 44 66

[[2]]
[1] 80 82 34

Upvotes: 0

Views: 134

Answers (1)

www
www

Reputation: 39154

In purrr, this can be done with map2.

library(purrr)

map2(nums_a, nums_b, ~.x + .y)
# [[1]]
# [1] 14 44 66
# 
# [[2]]
# [1] 80 82 34

Upvotes: 2

Related Questions