数据帧D1中的分类变量V1可以有从A到z的字母表示的值。我想创建一个子集D2,其中不包括一些值,比如B、N和t。基本上,我想要一个与%中的%相反的命令

D2 = subset(D1, V1 %in% c("B", "N", "T"))

当前回答

Purrr::compose()是另一种快速定义方法,以供以后使用,如下所示:

`%!in%` <- compose(`!`, `%in%`)

其他回答

使用negate from purrr也可以快速而整洁地达到目的:

`%not_in%` <- purrr::negate(`%in%`)

例如,用法是,

c("cat", "dog") %not_in% c("dog", "mouse")

如何:

`%ni%` <- Negate(`%in%`)
c(1,3,11) %ni% 1:10
# [1] FALSE FALSE  TRUE

包崩溃内置了:%!在%中。

library(roperators)

1 %ni% 2:10

如果经常需要使用自定义中缀操作符,那么在包中使用中缀操作符比在每个脚本或项目中反复声明相同的函数更容易。

如果你看%in%的代码

 function (x, table) match(x, table, nomatch = 0L) > 0L

然后你应该能够写出你的相反版本。我使用

`%not in%` <- function (x, table) is.na(match(x, table, nomatch=NA_integer_))

另一种方法是:

function (x, table) match(x, table, nomatch = 0L) == 0L