Home > Software design >  Getting rid of NA in paste command in R
Getting rid of NA in paste command in R

Time:12-07

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::str_glue(a, b)) Does not work

CodePudding user response:

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, "")))

CodePudding user response:

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 "    

CodePudding user response:

Using base R.

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