0

I am looking for a solution to convert all to blank(' ') for all character columns in the data frame. I would prefer Base R solution. I tried solution described in (Setting <NA> to blank ) but it requires to convert entire data frame as a factor and that creates an issue for numeric columns e.g.

df <- data.frame(x=c(1,2,NA), y=c("a","b",NA))

To convert numeric NA to 0

df[is.na(df)] <- 0   

To convert character to Blank(" ") - It converts all columns to character.

df <- sapply(df, as.character)
df[is.na(df)] <- " "
dc37
  • 15,840
  • 4
  • 15
  • 32
R007
  • 101
  • 1
  • 13

2 Answers2

2

It's maybe not the most elegant way but using dplyr, you can convert all factor column to character column using mutate_if and then replace all NA by "" in character columns by using ifelse in mutate_if:

library(dplyr)
df %>% mutate_if(is.factor, ~as.character(.)) %>%
  mutate_if(is.character, ~ifelse(is.na(.)," ",.))

   x y
1  1 a
2  2 b
3 NA  
dc37
  • 15,840
  • 4
  • 15
  • 32
2

Create your dataframe with stringsAsFactors = FALSE

df <- data.frame(x=c(1,2,NA), y=c("a","b",NA), stringsAsFactors = FALSE)

Find character columns

cols <- sapply(df, is.character)

Turn them to blank

df[cols][is.na(df[cols])] <- ' '
df

#   x y
#1  1 a
#2  2 b
#3 NA  
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213