Faster %in% operator

前端 未结 2 627
太阳男子
太阳男子 2021-02-07 00:55

The fastmatch package implements a much faster version of match for repeated matches (e.g. in a loop):

set.seed(1)
library(fastmatch)
table <- 1L         


        
2条回答
  •  一个人的身影
    2021-02-07 01:48

    Look at the definition of %in%:

    R> `%in%`
    function (x, table) 
    match(x, table, nomatch = 0L) > 0L
    
    
    

    It's easy to write your own %fin% function:

    `%fin%` <- function(x, table) {
      stopifnot(require(fastmatch))
      fmatch(x, table, nomatch = 0L) > 0L
    }
    system.time(for(i in 1:100) a <- x %in% table)
    #    user  system elapsed 
    #   1.780   0.000   1.782 
    system.time(for(i in 1:100) b <- x %fin% table)
    #    user  system elapsed 
    #   0.052   0.000   0.054
    identical(a, b)
    # [1] TRUE
    

提交回复
热议问题