Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum of two lists with lists in R

Tags:

list

r

sum

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?

like image 880
Jetse Avatar asked Mar 07 '13 14:03

Jetse


People also ask

How do you add two lists in R?

combine. lists is an R function developped combine/append two lists, with special attention to dimensions present in both. combine. lists(list1, list2) returns a list consisting in the elements found in either list1 or list2, giving precedence to values found in list2 for dimensions found in both lists.

How do I add all elements to a vector in R?

Use append() function to add a single element or multiple elements to the vector. A vector in R is a sequence of data elements of the same data type.

Can you sum two lists in Python?

The sum() function is used to add two lists using the index number of the list elements grouped by the zip() function. A zip() function is used in the sum() function to group list elements using index-wise lists. Let's consider a program to add the list elements using the zip function and sum function in Python.


2 Answers

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]))
like image 144
agstudy Avatar answered Oct 04 '22 00:10

agstudy


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

  mapply(function(x1, y1) x1[[1]]+y1[[1]], x, y)
like image 30
Ricardo Saporta Avatar answered Oct 04 '22 00:10

Ricardo Saporta