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

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

当前回答

如果你看%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

其他回答

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

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

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

如何:

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

另一个解决方案是使用setdiff

D1 = c("A",..., "Z") ; D0 = c("B","N","T")

D2 = setdiff(D1, D0)

D2是你想要的子集。

如果你看%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