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.
This is the formula for the addition of vectors: Given two vectors a = (a1, a2) and b = (b1, b2), then the vector sum is, M = (a1 + b1, a2 + b2) = (Mx, My).
To add or subtract two vectors, add or subtract the corresponding components. Let →u=⟨u1,u2⟩ and →v=⟨v1,v2⟩ be two vectors. The sum of two or more vectors is called the resultant. The resultant of two vectors can be found using either the parallelogram method or the triangle method .
To put it simply, you can only add quantities with the same units, example, weight to weight (or mass to mass), time to time, money to money, etc. It is the same thing with vectors. Acceleration and velocity are both vectors, but with different units, so should not be added.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With