5

假设您有一个向量列表:

L = list()
L[[1]]= c(2,34,6,7,3)
L[[2]]= c(3,4,6,8,1)
names(L[[1]])=c("A","B","C","D","E")
names(L[[2]])=c("A","R","C","D","F")
L

## [[1]]
##  A  B  C  D  E 
##  2 34  6  7  3 
## 
## [[2]]
## A R C D F 
## 3 4 6 8 1 

我想按每个元素的名称对 2 个向量求和...结果:

A  B  C  D  E  F  R
5 34 12 15  3  1  4  

谢谢

4

2 回答 2

10

另一种解决方案使用tapply

> tapply(unlist(L), names(unlist(L)), sum)
 A  B  C  D  E  F  R 
 5 34 12 15  3  1  4 

编辑

即使您的向量具有不同的长度,它也会起作用,请参见示例:

> L = list()
> L[[1]]= 1:10
> L[[2]]= c(3,4,6,8,1)
> names(L[[1]])=LETTERS[1:10]
> names(L[[2]])=c("A","R","C","D","F")

> tapply(unlist(L), names(unlist(L)), sum)
 A  B  C  D  E  F  G  H  I  J  R 
 4  2  9 12  5  7  7  8  9 10  4  # IT WORKS!!!
于 2013-05-16T16:31:03.960 回答
2
 x <- aggregate(unlist(L), by=list(names(unlist(L))), FUN=sum)
result <- x$x
names(result) <- x$Group.1
result
## A  B  C  D  E  F  R 
## 5 34 12 15  3  1  4 
于 2013-05-16T16:23:08.197 回答