首页 > 解决方案 > 跨多列的逻辑向量

问题描述

我正在尝试跨 data.table 中的许多列运行逻辑或语句,但在编写代码时遇到了麻烦。我的列具有如下表所示的模式。如果需要,我可以使用常规逻辑向量,但我想知道是否可以找到一种遍历 a1、a2、a3 等的方法,因为我的实际数据集有许多“a”类型的列。

提前致谢。

library(data.table)
x <- data.table(a1 = c(1, 4, 5, 6), a2 = c(2, 4, 1, 10), z = c(9, 10, 12, 12))

# this works but does not work for lots of a1, a2, a3 colnames 
# because code is too long and unwieldy
x[a1 == 1 | a2 == 1 , b:= 1] 

# this is broken and returns the following error
x[colnames(x)[grep("a", names(x))] == 1, b := 1] 
Error in `[.data.table`(x, colnames(x)[grep("a", names(x))] == 1, `:=`(b,  : 
  i evaluates to a logical vector length 2 but there are 4 rows. Recycling of logical i is no longer allowed as it hides more bugs than is worth the rare convenience. Explicitly use rep(...,length=.N) if you really need to recycle.

输出如下所示:

   a1 a2  z  b
1:  1  2  9  1
2:  4  4 10 NA
3:  5  1 12  1
4:  6 10 12 NA

标签: rdata.table

解决方案


尝试使用面具:

x$b <- 0
x[rowSums(ifelse(x[, list(a1, a2)] == 1, 1, 0)) > 0, b := 1]

现在假设您有 100a列,它们是数据表中的前 100 列。然后您可以使用以下方法选择列:

x[rowSums(ifelse(x[, c(1:100)] == 1, 1, 0) > 0, b := 1]

ifelse(x[, list(a1, a2)] == 1, 1, 0)返回一个数据表,其中只有列1中有 a1的值a。然后我使用 rowSums 进行水平求和,如果这些总和中的任何一个为> 0,则表示1给定行的至少一列中有 a,因此我只需选择这些行并将其设置b1


推荐阅读