Jetse
Jetse

Reputation: 1816

sum of two lists with lists in R

Is there an easy way to do a simple calculation in a list of lists?

x <- list(a=list(1:4),b=list(1:6))
y <- list(a=list(1:4),b=list(1:6))

When I try:

x+y

I receive the error: Error in x + y : non-numeric argument to binary operator

X and y are equal lengths, and contain only integers. With a matrix it is possible to do y+x, is there a way to do this for lists with lists?

Upvotes: 13

Views: 7604

Answers (2)

agstudy
agstudy

Reputation: 121578

You can use lapply to go through each 2 lists simultaneously.

 lapply(seq_along(x),function(i)
         unlist(x[i])+unlist(y[i]))

[[1]]
a1 a2 a3 a4 
 2  4  6  8 

[[2]]
b1 b2 b3 b4 b5 b6 
 2  4  6  8 10 12 

if x and y don't have the same length, you can do this :

 lapply(seq_len(min(length(x),length(y)),function(i)
         unlist(x[i])+unlist(y[i]))

Upvotes: 10

Ricardo Saporta
Ricardo Saporta

Reputation: 55360

assuming each list has the same structure, you can use mapply as follows

  mapply(function(x1, y1) x1[[1]]+y1[[1]], x, y)

Upvotes: 10

Related Questions