总和矢量与相应的名称

时间:2013-05-16 16:17:52

标签: r vector sum

假设你有一个矢量列表:

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  

谢谢

2 个答案:

答案 0 :(得分:6)

使用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!!!

答案 1 :(得分: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