0

How do I replace NA values by - in my code below:

library(dplyr)

output<-structure(list(date = structure(c(18808, 18810), class = "Date"), 
               ABC = c(4, 1), CDE = c(1, NA), FGH = c(6, NA)), row.names = c(NA, 
                                                                             -2L), class = "data.frame")
output<-output %>% mutate(SUM = rowSums(across(2:last_col()), na.rm = TRUE))

> output
        date ABC CDE FGH SUM
1 2021-06-30   4   1   6  11
2 2021-07-02   1  NA  NA   1

3 Answers3

2

In base R, we may do

output[is.na(output)] <- "-"

-output

> output
        date ABC CDE FGH SUM
1 2021-06-30   4   1   6  11
2 2021-07-02   1   -   -   1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks! For this case it worked, another example when I do this it gives the following error: `Error: Assigned data "-" must be compatible with existing data. i Error occurred for column x Can't convert to . Run rlang::last_error() to see where the error occurred.` Do you know how to adjust this? –  Oct 18 '21 at 17:39
  • @CarlosJoseph It will have a problem in case of tidyverse functions. But, here we are using just `base R` and it does automatically change the type though – akrun Oct 18 '21 at 17:41
  • @CarlosJoseph Can you show an example where this doesn't work – akrun Oct 18 '21 at 17:46
  • @CarlosJoseph can you tell me what was the issue – akrun Oct 18 '21 at 18:04
2

If you're going to eventually run the data.frame through knitr::kable() to get a formatted table, you can add this line to your script:

options(knitr.kable.NA = "--")

Then, the formatted table (html, pdf, etc) will have long dashes instead of NAs, but the underlying data.frame will not be modified.

Dave Braze
  • 441
  • 3
  • 14
1

Does this work:

library(dplyr)
library(tidyr)
output %>% mutate(SUM = rowSums(across(2:last_col()), na.rm = TRUE)) %>% 
  mutate(across(everything(), ~ replace_na(as.character(.), '-')))
        date ABC CDE FGH SUM
1 2021-06-30   4   1   6  11
2 2021-07-02   1   -   -   1
Karthik S
  • 11,348
  • 2
  • 11
  • 25