Alexander
Alexander

Reputation: 4635

R: Counting rows based on logical checking (<0 & >0)

For given dt I would like to count some of specific rows by comparing another column.

here is what I mean;

library(data.table)
dt <- data.table(a=c(0.98,-0.97,0.95,-0.92,-0.82,-0.7,0.6,-0.8,0.4,0.92),b=c(0.98,-0.92,-0.94,0.91,-0.90,0.7,-0.67,-0.62,-0.66,0.84))


#> dt
#        a     b
# 1:  0.98  0.98
# 2: -0.97 -0.92
# 3:  0.95 -0.94
# 4: -0.92  0.91
# 5: -0.82 -0.90
# 6: -0.70  0.70
# 7:  0.60 -0.67
# 8: -0.80 -0.62
# 9:  0.40 -0.66
#10:  0.92  0.84

I want to count only conditions a>0 & b<0 cases. So the count number should be 3

Upvotes: 1

Views: 59

Answers (3)

Snopzer
Snopzer

Reputation: 1692

Here is simple Process

sum(with(dt, a > 0  & b <0))

Upvotes: 2

akrun
akrun

Reputation: 887108

We can use the data.table way

dt[a >0 & b<0, .N]
#[1] 3

Upvotes: 4

Vincent Bonhomme
Vincent Bonhomme

Reputation: 7443

You can do it with:

sum(with(dt, a > 0  & b <0))

Upvotes: 3

Related Questions