因子水平的哪个函数

which function for factor levels

我想将 which 函数与 arr.ind = TRUE 一起用于 data.frame。如果我按列使用它,它会产生正确的结果。但是整个 data.frame.

我都无法得到这个

注意:我编辑了代码。此外,预期的输出已添加到代码中。

MWE:

df <- data.frame(f1 = factor(c("a","b","a","x","x")), 
                 f2 = factor(c("a","x","x","x","b")))

which(df %in% c("a","b"), arr.ind = TRUE)
# integer(0)  # This is not what I expect

# Expected output
# row col
#   1   1
#   2   1
#   3   1
#   1   2
#   5   2

这是一个方法:

x = as.matrix(df) %in% c("a", "b")
cbind(row(df)[x], col(df)[x])
#      [,1] [,2]
# [1,]    1    1
# [2,]    2    1
# [3,]    3    1
# [4,]    1    2
# [5,]    5    2

如果您打算替换这些值,逐列遍历整个数据框可能是最有效的(不使用此结果)。