【问题标题】:creating a new variable that combines several others using if else [duplicate]创建一个新变量,使用 if else [重复] 组合其他几个变量
【发布时间】:2018-03-24 17:33:18
【问题描述】:

我正在使用健康状况和结果的大型数据框架,我希望将 10 种健康状况组合成一个状况, 如果患者有 a、b、c 或 d 等,则条件为条件一。 我正在尝试这样编码:

      dataset$one <-  ifelse(dataset, (dataset$a == 1)|
                            (dataset$b == 1)|
                            (dataset$c  == 1)|
                            (dataset$d  == 1),  1, 0)

这似乎适用于第一个条件,但在我添加条件时不起作用。 也许 R 不允许多个 or 语句? 有什么建议么?

【问题讨论】:

  • 你可以试试ifelse(dataset, sum(dataset[c('a','b','c','d')] == 1) &gt;= 1, 1, 0)

标签: r if-statement recode


【解决方案1】:

假设dataset是一个数据框,定义列名cols,然后像这样在dataset[cols] == 1的每一行应用any。添加零以将结果从逻辑转换为数字:

cols <- c("a", "b", "c", "d")
dataset$one <- apply(dataset[cols] == 1, 1, any) + 0

注意事项

  1. 如果列具有您希望排除的 NA 值,则添加 na.rm = TRUE 参数:

    dataset$one <- apply(dataset[cols] == 1, 1, any, na.rm = TRUE) + 0
    
  2. Rfast 包有rowAny,如果你不需要na.rm,可以使用它:

    library(Rfast)
    dataset$one <- rowAny(dataset[cols] == 1) + 0
    

【讨论】:

  • Rfast 没有名为“anyRows”的函数...
  • 已将其更改为rowAny
【解决方案2】:

我们可以使用Reduce|

dataset$one <- as.integer(Reduce(`|`, lapply(dataset[c('a', 'b', 'c', 'd')], `==`, 1))

或者另一个选项是rowSums

dataset$one <- as.integer(rowSums(dataset[c('a', 'b', 'c', 'd')] == 1) > 0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 2023-04-07
    • 2021-04-23
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多