我正在尝试创建一个新的列,"condition_any",在df
{data。如果3个条件中的任何一个为TRUE,则该表}为TRUE,
我尝试使用any(.SD)
没有运气:
library(data.table)
df <- data.table(id = 1:3,
date = Sys.Date() + 1:3,
condition1 = c(T, F, F),
condition2 = c(T, F, T),
condition3 = c(F, F, F))
df[, condition_any := any(.SD), .SDcols = patterns("^condition")]
Error in FUN(X[[i]], ...) :
only defined on a data frame with all numeric variables
有什么好主意吗?我觉得这很容易做到。
感谢预期输出:
id date condition1 condition2 condition3 condition_any
1: 1 2021-02-12 TRUE TRUE FALSE TRUE
2: 2 2021-02-13 FALSE FALSE FALSE FALSE
3: 3 2021-02-14 FALSE TRUE FALSE TRUE
这也不使用any
,但这是一个很好的方法,
df[, condition_any := Reduce('|', .SD), .SDcols = patterns("^condition")]
我相信下面的代码会给你想要的。你可以查看这篇文章来查看错误的解释。
df$condition_any <- apply(df[,3:5], 1, function(x) any(x))
这使用any
并按预期工作,但它会很慢,因为它是按行分组数据。
library(data.table)
df[, condition_any := any(unlist(.SD)), .SDcols = patterns("^condition"),
1:nrow(df)]
df
# id date condition1 condition2 condition3 condition_any
#1: 1 2021-02-12 TRUE TRUE FALSE TRUE
#2: 2 2021-02-13 FALSE FALSE FALSE FALSE
#3: 3 2021-02-14 FALSE TRUE FALSE TRUE