Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding two vectors by names

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.

like image 738
Ricky Avatar asked Nov 18 '14 04:11

Ricky


People also ask

What is the formula for adding two vectors?

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).

How do you add the sum of two vectors?

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 .

Can you add 2 vectors with different units?

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.


1 Answers

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.)

like image 53
A5C1D2H2I1M1N2O1R2T1 Avatar answered Oct 18 '22 00:10

A5C1D2H2I1M1N2O1R2T1