【问题标题】:Getting rid of NA in paste command in R在R中的粘贴命令中摆脱NA
【发布时间】:2022-12-07 15:28:38
【问题描述】:

我想连接a和b。在缺少 a 和 b 的地方,我想在结果中只包含一个空字符串,而不是 NA 字符串...我从 glue 包中尝试了 str_glueglue 但没有成功。

library(dplyr)

df <- tibble(
  a = c(2010, 2019, NA, 2022),
  b = c(NA, 2018, 2022, NA)
)

df |>
  mutate(combined = paste(a, b))

# df |>
#   mutate(combined = stringr::str_glue(a, b)) Does not work

【问题讨论】:

    标签: r


    【解决方案1】:

    那么你可以使用dplyr库中的coalesce()

    library(dplyr)
    
    df
      %>% mutate(across(where(is.numeric), as.character))
      |> mutate(combined = paste(coalesce(a, ""), coalesce(b, "")))
    

    【讨论】:

    • mutate() 中的错误:!计算 combined = paste(coalesce(a, ""), coalesce(b, "")) 时出现问题。由coalesce()中的错误引起:!无法组合 ..1 <double> 和 ..2 <character>。
    • 您想显示什么值而不是NA
    • 我不想出现任何东西(只是“”)
    • 然后首先将数字列转换为字符,然后使用我的建议。
    【解决方案2】:

    另一种方法:

    df %>% mutate_if(is.numeric, as.character) %>% mutate(combine = paste(replace_na(a, ''), replace_na(b, '')))
    # A tibble: 4 × 3
      a     b     combine    
      <chr> <chr> <chr>      
    1 2010  NA    "2010 "    
    2 2019  2018  "2019 2018"
    3 NA    2022  " 2022"    
    4 2022  NA    "2022 "    
    

    【讨论】:

      猜你喜欢
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 2014-12-13
      相关资源
      最近更新 更多