Adding two vectors by names

2.1k views Asked by At

I have two named vectors

v1 <- 1:4
v2 <- 3:5
names(v1) <- c("a", "b", "c", "d")
names(v2) <- c("c", "e", "d")

I want to add them up by the names, i.e. the expected result is

> v3  
a b c d e   
1 2 6 9 4

Is there a way to programmatically do this in R? Note the names may not necessarily be in a sorted order, like in v2 above.

1

There are 1 answers

3
A5C1D2H2I1M1N2O1R2T1 On BEST ANSWER

Just combine the vectors (using c, for example) and use tapply:

v3 <- c(v1, v2)
tapply(v3, names(v3), sum)
# a b c d e 
# 1 2 6 9 4 

Or, for fun (since you're just doing sum), continuing with "v3":

xtabs(v3 ~ names(v3))
# names(v3)
# a b c d e 
# 1 2 6 9 4

I suppose with "data.table" you could also do something like:

library(data.table)
as.data.table(Reduce(c, mget(ls(pattern = "v\\d"))), 
              keep.rownames = TRUE)[, list(V2 = sum(V2)), by = V1]
#    V1 V2
# 1:  a  1
# 2:  b  2
# 3:  c  6
# 4:  d  9
# 5:  e  4

(I shared the latter not so much for "data.table" but to show an automated way of capturing the vectors of interest.)