【问题标题】:if_else does not return NA as expected (returns false condition instead)if_else 未按预期返回 NA(而是返回错误条件)
【发布时间】:2021-03-26 00:57:29
【问题描述】:

我已经看到几个围绕这个问题的问题,但似乎没有一个直接解决这个问题。

我在数据框列中有字符数据,一些值为NAif_else() 帮助文件示例演示它将把 NA 保留为 NA,除非使用 missing 参数另外指定。

但是,在我的情况下,它将NA 视为满足false 参数标准,并以这种方式返回。这是预期的行为吗?是因为使用字符数据吗?我能够从带有整数数据的帮助文件代码中看到预期的行为。

我查了str(my_df$test_vector),是字符数据,不是因子数据。

提前感谢论坛大师。

例子:

> test_vector <- c("1dose", "2dose", "yes", "no", "undecided", NA) # data as it appears in my dataframe
> is.na(test_vector)  # behaves as expected
[1] FALSE FALSE FALSE FALSE FALSE  TRUE 
> if_else(test_vector %in% c("1dose", "2dose", "yes"), "yes", "no")  # does not behave as expected
[1] "yes" "yes" "yes" "no"  "no"  "no"
> if_else(test_vector %in% c("1dose", "2dose", "yes"), "yes", "no", NA_character_)  # also unexpected
[1] "yes" "yes" "yes" "no"  "no"  "no" 

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    运算符 %in% 对 NA 值返回 false:

    test_vector %in% c("1dose", "2dose", "yes")
    [1]  TRUE  TRUE  TRUE FALSE FALSE FALSE
    

    我相信 str_detect 会给你你正在寻找的行为:

    > if_else(str_detect(test_vector, c("1dose", "2dose", "yes")),"yes","no")
    [1] "yes" "yes" "yes" "no"  "no"  NA
    

    【讨论】:

    • 来自 %in% 的帮助 - “%in% 永远不会返回 NA,这使得它在 if 条件下特别有用。”
    • 小心它也很危险。如果在顺序操作中使用,您可以人为地去除 NAs
    • 这太棒了,感谢您挑选出这个细节。我会更加勤奋地检查我所有的中间步骤!很容易忘记 %in% 在视觉上如此之小时起着重要作用。干杯。
    【解决方案2】:

    您发现的问题与 %in% 运算符的行为有关,而不是 if_else() 函数。将任何内容与 NA 进行比较时,%in% 返回 FALSE。

    test_vector <- c("1dose", "2dose", "yes", "no", "undecided", NA)
    
    > if_else(test_vector=='yes', 1, 0)
    [1]  0  0  1  0  0 NA
    
    > if_else(test_vector %in% 'yes', 1, 0)
    [1] 0 0 1 0 0 0
    

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 1970-01-01
      • 2022-06-30
      • 2012-10-05
      • 2017-03-31
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多