满足某些条件的列数或列数

时间:2019-10-04 14:18:44

标签: r count criteria

我想创建一个新列,该列计算特定列中满足的条件数。

例如,使用mtcars,条件可能如下: "disp" > 150, "hp < 100", "wt" > 2.65

在前三行-马自达RX4,马自达RX4 Wag和达特桑710-新列mtcars$metcri分别应为1、2和1。

我看过其他几篇文章,其中大多数集中在子集counting the total number of rows that match the criteria或使用one criteria across all the columns of concern上。我确实看到有一些重新使用if_else statements的东西,但这没用,新列的结果为52。以防万一我错过了一些东西,下面是代码:

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))

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

您可以直接添加三个逻辑条件

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

答案 1 :(得分:0)

我们可以使用with

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

或使用data.table

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