Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum vector with corresponding name

Tags:

r

vector

sum

Let say you have a list of vector:

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 

And I want to sum the 2 vectors by the name of each element... Results:

A  B  C  D  E  F  R
5 34 12 15  3  1  4  

Thank you

like image 653
joel lapalme Avatar asked May 16 '13 16:05

joel lapalme


People also ask

How do you sum a vector?

The triangle law of the addition of vectors states that two vectors can be added together by placing them together in such a way that the first vector's head joins the tail of the second vector. Thus, by joining the first vector's tail to the head of the second vector, we can obtain the resultant sum vector.

Is sum () a vectorized function?

No. For example, if you write the statement s=sum(v), you are calling a function and that is not vectorized code. The function sum may or may not use vectorized code to do the summing, but the function call that you write is just that, a function call—it does not perform an operation on multiple components.

How do I sum everything in a vector in R?

The sum() is a built-in R function that calculates the sum of a numeric input vector. It accepts a numeric vector as an argument and returns the sum of the vector elements. To calculate the sum of vectors in R, use the sum() function.

How do you find the sum of two vectors in R?

We can add two vectors together using the + operator. One thing to keep in mind while adding (or other arithmetic operations) two vectors together is the recycling rule. If the two vectors are of equal length then there is no issue.


1 Answers

Another solution using tapply

> tapply(unlist(L), names(unlist(L)), sum)
 A  B  C  D  E  F  R 
 5 34 12 15  3  1  4 

EDIT

It will work even if your vectors have different lengths, see the example:

> 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!!!
like image 75
Jilber Urbina Avatar answered Sep 22 '22 10:09

Jilber Urbina