Wei
Wei

Reputation: 151

How do I sum a specific value from a particular column given other criteria in R?

Let's say I have the following table:

> df <- data.frame("1"=c(9,10,11,10,11,9,10,10,9,11), "2"=c(1,1,2,2,1,2,1,2,2,1), "3"=c(3,1,0,0,3,3,3,3,1,0))
> df
   X1 X2 X3
1   9  1  3
2  10  1  1
3  11  2  0
4  10  2  0
5  11  1  3
6   9  2  3
7  10  1  3
8  10  2  3
9   9  2  1
10 11  1  0

How do I find the sum of all the 3's in the column X3, given the criteria that the value in column X1 must be 9, and the value in column X2 is 1?

Upvotes: 0

Views: 32

Answers (1)

akrun
akrun

Reputation: 887881

We can use == with & to create a logical vector, get the sum and multiply by 3

with(df, 3 * sum(X3 == 3 & X1 == 9 & X2 == 1))
#[1] 3

Or another option is

3 * sum(do.call(paste0, df) == '913') 

Upvotes: 1

Related Questions