tora0515
tora0515

Reputation: 2547

How to count rows meeting a condition

Suppose I have the following data frame:

Data1
      X1     X2
1     15     1
2     3      1
3     7      0
4     11     1
5     1      0
6     9      0
7     18     0
8     6      1
9     3      1

I would like to know how to find the total number of observations where X1 is greater than 9 and X2 is equal to 1?

I think I will need to use sum(), but I have no idea what to put in the parenthesis.

Upvotes: 1

Views: 478

Answers (1)

aatrujillob
aatrujillob

Reputation: 4826

data1='
        X1     X2
        15     1
        3      1
        7      0
        11     1
        1      0
        9      0
        18     0
        6      1
        3      1'



data1=read.table(text=data1,header=T)    

1)

nrow(data1[data1$X1 > 9 & data1$X2 ==1,])

2)

sum(data1$X1 > 9 & data1$X2 ==1)

3)

With data.table:

dataDT = data.table(data1)
dataDT[X1 > 9 & X2 == 1, .N]

Upvotes: 3

Related Questions