SSV
SSV

Reputation: 139

how to add elements of data frame with their respective unique columns

enter image description here

I have data like this, in a data frame. Here 1 and 3 refer to name of states, which are unique. how do i add up values below them? I mean, in the image shown, my output should be 1 and 1500 and 3 and 500. basically add up values below 1 and consolidate it under 1 and add up values below 3 and sum it up under 3. i want to add the respective terms and unable to do it. any resource or help would be much appreciated.

Upvotes: 2

Views: 28

Answers (1)

Florian
Florian

Reputation: 25385

You could try the following:

df = data.frame(A=c(1,500),B=c(3,300),C=c(3,200),D=c(1,500),E=c(1,500))
tapply(as.numeric(df[2,]),as.factor(df[1,]), sum)

Output:

   1    3 
1500  500 

Upvotes: 2

Related Questions