Add respective dataframes in list together in R

2019-08-09 11:52发布

问题:

I have 2 lists of dataframes in R (where the respective dataframes in each list are the same size). Is it possible to add the respective dataframnes in each list together in one line.

e.g. say we had

list1 <- list('a' = data.frame('x'=c(0,1),'y'=c(2,0)), 'b' = data.frame('x'=c(1,1),'y'=c(1,1)))
list2 <- list('a' = data.frame('x'=c(1,2),'y'=c(1,1)), 'b' = data.frame('x'=c(0,1),'y'=c(0,1)))

So list1 is:

$a
 x y
 0 2
 1 0

$b
 x y
 1 1
 1 1

And list2 is:

$a
 x y
 1 1
 2 1

$b
 x y
 0 0
 1 1

The final output would be:

$a
 x y
 1 3
 3 1

$b
 x y
 1 1
 2 2

Could obviously do this in two seperate lines by doing:

listOutput <- list()
listOutput[['a']] <- list1[['a']] + list2[['a']]
listOutput[['b']] <- list1[['b']] + list2[['b']]

but is there a simple way to do this in one line, maybe using lapply?

Thanks

回答1:

Here's a way that preserves names:

mapply(function(x, y) x + y, list1, list2, SIMPLIFY=FALSE, USE.NAMES=TRUE)


回答2:

Here is a solution that is very specific to your question. In other words, it assumes:

  1. You have two lists
  2. Each list has identical elements
  3. The elements can be converted to matrices

The code:

lapply(1:2, function(i)list1[[i]] + list2[[i]])
[[1]]
  x y
1 1 3
2 3 1

[[2]]
  x y
1 1 1
2 2 2


回答3:

In theory, you should be able to do it with a combination of unlist and relist, but it doesn't seem to work as documented:

relist(unlist(list1)+unlist(list2),skeleton=list1)
$a
   x    y <NA> <NA> 
   1    3    3    1 

$b
   x    y <NA> <NA> 
   1    2    1    2