【问题标题】:Use coalesce inside ifelse in R在 R 中的 ifelse 中使用合并
【发布时间】:2021-05-07 21:44:20
【问题描述】:

谁能解释一下以下代码的奇怪输出? 我有一个带有一些 NA 的数据集。我想使用 C 列中的值(如果存在), 填写 B 列中的 NA。使用时,coalesce 功能正常工作 没有 ifelse,但在 ifelse 函数中使用时,结果很奇怪。

library(tidyverse)

x <- tibble(A = 1:3, 
            B = c("first", NA, "third"),
            C = c("first", "second", NA))

x %>%
    mutate(B = coalesce(B, C))
#> # A tibble: 3 x 3
#>       A B      C     
#>   <int> <chr>  <chr> 
#> 1     1 first  first 
#> 2     2 second second
#> 3     3 third  <NA>

x %>%
    mutate(B = ifelse(has_name(., "C"), coalesce(B, C), B))
#> # A tibble: 3 x 3
#>       A B     C     
#>   <int> <chr> <chr> 
#> 1     1 first first 
#> 2     2 first second
#> 3     3 first <NA>

我用下面的代码解决了这个问题:

if(has_name(x, "C")){
    x %>%
        mutate(B = coalesce(B, C))
}           
#> # A tibble: 3 x 3
#>       A B      C     
#>   <int> <chr>  <chr> 
#> 1     1 first  first 
#> 2     2 second second
#> 3     3 third  <NA>  

但我想在 mutate 函数中使用 if 语句。任何澄清都非常感谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以在mutate 中使用if/else

    library(dplyr)
    x %>%
        mutate(B = if(has_name(., "C")) coalesce(B, C) else  B)
    

    -输出

    # A tibble: 3 x 3
    #       A B      C     
    #  <int> <chr>  <chr> 
    #1     1 first  first 
    #2     2 second second
    #3     3 third  <NA>  
    

    注意ifelse 要求所有参数的长度相同,has_name 输出是length 1 的逻辑向量,而其他则不是。

    【讨论】:

    • 谢谢! ifelse 和 if/else 有什么区别?
    • @mchiapello 不同之处在于if/else 没有向量化,即它只接受长度为1 的输入逻辑向量,而ifelse 可以采用&gt; 1。但是有一个约束,即所有参数应该具有相同的长度,否则会发生回收(如果对象也具有不同的结构,那么if/else 更好)
    猜你喜欢
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2020-04-20
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    相关资源
    最近更新 更多