R how many element satisfy a condition?

前端 未结 3 1813
忘掉有多难
忘掉有多难 2020-12-18 23:20

Is there a better way to count how many elements of a result satisfy a condition?

a <- c(1:5, 1:-3, 1, 2, 3, 4, 5)
b <- c(6:-8)
u <- a > b
length         


        
3条回答
  •  时光说笑
    2020-12-18 23:58

    sum does this directly, counting the number of TRUE values in a logical vector:

    sum(u, na.rm=TRUE)
    

    And of course there is no need to construct u for this:

    sum(a > b, na.rm=TRUE)
    

    works just as well. sum will return NA by default if any of the values are NA. na.rm=TRUE ignores NA values in the sum (for logical or numeric).

提交回复
热议问题