我正在查找 data.table 中包含任意多个变量的行。我当前的代码可以工作,但有点困惑:
#dt contains several columns, foo1, foo2, foo3, etc that have the same possible values
#Values I am searching for
bar <- ("a","b","c")
#current method
dt[foo1 %in% bar| foo2 %in% bar | foo3 %in% bar ...]
这个方法可行,但我想知道是否有更有效的方法来做到这一点。
最佳答案
您可以将 lapply
与 .SD
和 Reduce
一起使用 -
library(data.table)
dt[, .SD[Reduce(`|`, lapply(.SD, `%in%`, bar))]]
关于r - 检查多个变量中是否存在相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68347980/