R how many element satisfy a condition?

前端 未结 3 1814
忘掉有多难
忘掉有多难 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:33

    If z consists of only TRUE or FALSE, then simply

    length(which(z))
    
    0 讨论(0)
  • 2020-12-18 23:39

    I've always used table for this:

    a <- c(1:5, 1:-3, 1, 2, 3, 4, 5)
    b <- c(6:-8)
    table(a>b)
    FALSE  TRUE 
        8     7 
    
    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题