r - 跨多列的逻辑向量
问题描述
我正在尝试跨 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
解决方案
尝试使用面具:
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,因此我只需选择这些行并将其设置b
为1
。
推荐阅读
- javascript - 猫头鹰旋转木马 | 如何使用 CSS 更改 .Item 的大小
- excel - 显示重复总计的 PowerPivot 表关系
- rx-java - rxJava:仅当所有 Flowables 都被消耗时才运行代码
- python - 如何在 Python 中将输入存储在两个不同的数组中
- android - 如何保持会话活跃?Android 库离子
- python - 如何在 django 的 admin.py 文件中注册继承的子类?
- php - Update database when I submit button HTML / PHP
- php - 在php中无法访问关联数组
- java - 单击日历时如何在调度程序视图中获取资源
- swift - 如何在一系列问题的标签中显示下一个问题