为什么我可以在一种情况下使用双变量过滤因子变量,而在另一种情况下不能?
示例数据如下:
dt <- data.table(id=1:9,
var=factor(81:89))
# > dt
# id var
# 1: 1 81
# 2: 2 82
# 3: 3 83
# 4: 4 84
# 5: 5 85
# 6: 6 86
# 7: 7 87
# 8: 8 88
# 9: 9 89
为什么这个工作...
dt[id %in% 1:7 & var %in% c(82, 84)]
# id var
# 1: 2 82
# 2: 4 84
...但这会出错?
dt[var %in% c(82, 84)]
# Error in bmerge(i, x, leftcols, rightcols, io <- FALSE, xo, roll = 0, :
# x.'var' is a factor column being joined to i.'V1' which is type 'double'.
# Factor columns must join to factor or character columns.`
似乎有点无关紧要,可能是一个错误?
最佳答案
不同的是,第二个例子是通过自动索引优化的,会抛出这个错误。您可以像这样关闭此功能:
dt[(var %in% c(82, 84))]
# id var
#1: 2 82
#2: 4 84
然后使用基本 R 向量扫描并应用通常的强制规则。来自
help("%in%")
:Factors, raw vectors and lists are converted to character vectors, and then x and table are coerced to a common type
var <- factor(81:89)
var %in% c(82, 84)
#[1] FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE FALSE
问题已经fixed在数据表版本 1.9.7 中。
关于r - 在 R data.table 中使用双变量过滤因子变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38659602/