在R中将列表中的各个数据帧一起添加 [英] Add respective dataframes in list together in R

查看:87
本文介绍了在R中将列表中的各个数据帧一起添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在R中有2个数据帧列表(其中每个列表中的各个数据帧具有相同的大小).是否可以在一行中将每个列表中的相应数据帧一起添加.

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.

例如说我们有

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)))

所以list1是:

$a
 x y
 0 2
 1 0

$b
 x y
 1 1
 1 1

list2是:

$a
 x y
 1 1
 2 1

$b
 x y
 0 0
 1 1

最终输出将是:

$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']]

但是有一种简单的方法可以在一行中执行此操作,也许使用lapply吗?

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

谢谢

推荐答案

以下是保存名称的方法:

Here's a way that preserves names:

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

这篇关于在R中将列表中的各个数据帧一起添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆