【问题标题】:if else with multiple conditions combined with AND and ORif else 有多个条件并结合 AND 和 OR
【发布时间】:2017-06-04 15:45:53
【问题描述】:

我正在寻找一种方法来创建一个新变量 (1,0),其中 1 用于结合 AND 和 OR 的多个条件。

即如果

a > 3 和 b > 5

c > 3 和 d > 5

e > 3 和 f > 5

1

如果不是

0

我尝试将其编码为;

df$newvar <- ifelse(df$a > 3 & df$b > 5 | df$c > 3 & df$d > 5 | df$e > 3 & df$f > 5,"1","0")

但在我的输出中,许多变量被编码为 NA 并且数字似乎没有相加。

有没有人对正确的编码方式提出建议?

【问题讨论】:

  • 如果您的列中有 NA,请使用 &amp; is.na(df$a)

标签: r


【解决方案1】:

我们可以对列进行子集化以评估大于 3 的值,得到逻辑 vectors ('l1') 的 list,类似地对于大于 5 的值 ('l2'),然后比较相应的元素list 使用 MapReduce 将其转换为单个 vector。使用as.integer,我们将逻辑向量强制为二进制

l1 <- lapply(df[c('a', 'c', 'e')] , function(x) x > 3 & !is.na(x))
l2 <- lapply(df[c('b', 'd', 'f')], function(x) x > 5 & !is.na(x))
df$newvar <- as.integer(Reduce(`|`, Map(`&`, l1, l2)))
df$newvar
#[1] 0 0 1 1 0 1 0 0 1 0

或者使用OP的方法

with(df, as.integer((a >3 & !is.na(a) & b > 5 & !is.na(b)) | (c > 3 & !is.na(c) &
        d > 5 & !is.na(d)) | (e > 3 & !is.na(e) & f > 5 & !is.na(f))))
#[1] 0 0 1 1 0 1 0 0 1 0

数据

set.seed(24)
df <- as.data.frame(matrix(sample(c(NA, 1:8), 6 * 10, replace = TRUE), 
                ncol = 6, dimnames = list(NULL, letters[1:6])))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 2012-08-03
    • 2012-05-06
    • 1970-01-01
    • 2015-09-17
    • 1970-01-01
    相关资源
    最近更新 更多