Search code examples
rlistaddition

How to add two vectors together to get a list in R


I am attempting to add two vectors together. How do I return all results of a vector added to another vector in list format? Like so:

a = c(1:4)
b = c(5:8)

where expected result is the following list resulted from a+b:

list(c(6,7,8,9),
     c(7,8,9,10),
     c(8,9,10,11),
     c(9,10,11,12))

#> [[1]]
#> [1] 6 7 8 9
#> 
#> [[2]]
#> [1]  7  8  9 10
#> 
#> [[3]]
#> [1]  8  9 10 11
#> 
#> [[4]]
#> [1]  9 10 11 12

Solution

  • a <- c(1:4)
    b <- c(5:8)
    
    lapply(a, function(x){x+b})