开发者

Getting rid of NA in paste command in R

I would like to concatenate a and b. Where a and b are missing I would like to have just an empty string in the result not NA string... I unsuccessfully tried str_glue and glue from glue package.

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开发者_JAVA技巧::str_glue(a, b)) Does not work


Well you could use coalesce() from the dplyr library:

library(dplyr)

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


Another approach:

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 "    


Using base R.

trimws(Reduce(paste, {df[is.na(df)] <- ''; df}))
# [1] "2010"      "2019 2018" "2022"      "2022"     
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜