Ardeshir
Ardeshir

Reputation: 11

Count or the Number of Columns That Meet Some Criteria

I'd like to create a new column that counts the number of conditions met across specific columns.

For example, using mtcars, the conditions might be as follows: "disp" > 150, "hp < 100", "wt" > 2.65

Looking at the top three rows - Mazda RX4, Mazda RX4 Wag, Datsun 710 - the new column, mtcars$metcri, should be 1, 2, and 1, respectively.

I've looked at a number of other articles and most focus on subsetting, counting the total number of rows that match the criteria, or using one criteria across all the columns of concern. I did see something re using if_else statements, but that didn't work and yielded 52 for the new column. Just in case I missed something, here is the code for that:

mtcars$metcri <- sum(if_else(mtcars$disp > 150, 1, 0, missing = NULL), 
                      if_else(mtcars$hp < 100, 1, 0, missing = NULL), 
                      if_else(mtcars$wt > 2.65, 1, 0, missing = NULL))

Any help would be greatly appreciated.

Upvotes: 1

Views: 210

Answers (2)

akrun
akrun

Reputation: 887751

We can use with

mtcars$metcri <- with(mtcars, disp > 150 + hp < 100 + wt > 2.5)

Or using data.table

library(data.table)
as.data.table(mtcars)[, metcri := (disp > 150) + (hp < 100) + (wt > 2.5)]

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389235

You could add the three logical conditions directly

mtcars$metcri <- (mtcars$disp > 150)  +  (mtcars$hp < 100) + (mtcars$wt > 2.5)

Upvotes: 3

Related Questions