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.
Just combine the vectors (using
c
, for example) and usetapply
:Or, for fun (since you're just doing
sum
), continuing with "v3":I suppose with "data.table" you could also do something like:
(I shared the latter not so much for "data.table" but to show an automated way of capturing the vectors of interest.)