moodymudskipper / inops

Infix Operators for Detection, Subsetting and Replacement
GNU General Public License v3.0
40 stars 0 forks source link

`%in{}%` on (lists of) language objects #17

Closed moodymudskipper closed 4 years ago

moodymudskipper commented 5 years ago

library(rangeops)
#> 
#> Attaching package: 'rangeops'
#> The following object is masked from 'package:base':
#> 
#>     <<-
x <- quote(a)
# works
x == x
#> [1] TRUE
# doesn't
x %in% x
#> Error in match(x, table, nomatch = 0L): 'match' requires vector arguments
# doesn't either because it's based on `%in%`
x %in{}% x
#> Error in match(x, table, nomatch = 0L): 'match' requires vector arguments

# But shouldn't it work regarding our consistency principles with `==` ?

# the following seems to fix it :

`%in{}%` <- function(x, table) {
  if (is.atomic(x)) {
    res <- x %in% table
  } else {
    res <- lapply(x, function(a,b)
      if(is.language(a)) any(a == b) else a %in% b, table)
  }
  attributes(res) <- attributes(x)
  if (!is.language(x)) res[is.na(x)] <- NA
  simplify2array(res)
}

y <- quote(b)
x %in{}% x
#> [1] TRUE
x %in{}% y
#> [1] FALSE
x %in{}% c(x,y)
#> [1] TRUE

c(x,y) %in{}% x
#> [1]  TRUE FALSE
c(x,y) %in{}% y
#> [1] FALSE  TRUE
c(x,y) %in{}% c(x,y)
#> [1] TRUE TRUE

Created on 2019-09-27 by the reprex package (v0.3.0)

moodymudskipper commented 4 years ago

example above was using old version but principles applied, closed by 7d5f7deb135bfe1e59a0c9bab2ec88c43ee8b307