More efficient strategy for which() or match()

后端 未结 3 1677
情话喂你
情话喂你 2020-12-31 23:30

I have a vector of positive and negative numbers

vec<-c(seq(-100,-1), rep(0,20), seq(1,100))

the vector is larger than the example, and

3条回答
  •  忘掉有多难
    2021-01-01 00:14

    Use sum() and logical comparison:

    sum( vec < 0 )
    [1] 100
    

    This will be pretty quick, and when you sum a logical, TRUE is 1 and FALSE is 0 so the total will be the number of negative values.

    Uh oh, I feel the need for a benchmarking comparison... :-) Vector length is 2e5

    library(microbenchmark)
    vec<-c(seq(-100,-1,length.out=1e5), rep(0,20), seq(1,100,length.out=1e5))
    microbenchmark( (which.min(vec < 0) - 1L) , (sum( vec < 0 )) )
    
    Unit: milliseconds
                          expr      min       lq   median       uq       max neval
     (which.min(vec < 0) - 1L) 1.883847 2.130746 2.554725 3.141787 75.943911   100
                (sum(vec < 0)) 1.398100 1.500639 1.508688 1.745088  2.662164   100
    

提交回复
热议问题