0

I'm trying to replace all the NAs present in the column of integer type with 0 and NAs present in the column of factor type with empty string "". The code below is the one that i'm using but it doesn't seem to work

for(i in 1:ncol(credits)){
if(sapply(credits[i], class) == 'integer'){
    credits[is.na(credits[,i]), i] <- 0
}
else if(sapply(credits[i], class) == 'factor'){
    credits[is.na(credits[,i]), i] <- ''
}
  • 1
    Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). This will make it much easier for others to help you. – Sotos Jul 09 '20 at 06:43

2 Answers2

2

You can use across in dplyr to replace column values by class :

library(dplyr)

df %>%
  mutate(across(where(is.factor), ~replace(as.character(.), is.na(.), '')),
         across(where(is.numeric), ~replace(., is.na(.), 0)))


#  a b
#1 1 a
#2 2 b
#3 0 c
#4 4 d
#5 5  

b column is of class "character" now, if you need it as factor, you can add factor outside replace like :

across(where(is.factor), ~factor(replace(as.character(.), is.na(.), ''))),

data

df <- data.frame(a = c(1, 2, NA, 4:5), b = c(letters[1:4], NA), 
                 stringsAsFactors = TRUE)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

Another way of achieving the same:

library(dplyr)

# Dataframe
df <- data.frame(x = c(1, 2, NA, 4:5), y = c('a',NA, 'd','e','f'), 
             stringsAsFactors = TRUE)

# Creating new columns
df_final<- df %>% 
  mutate(new_x = ifelse(is.numeric(x)==TRUE & is.na(x)==TRUE,0,x)) %>% 
  mutate(new_y = ifelse(is.factor(y)==TRUE & is.na(y)==TRUE,"",y))

# Printing the output
df_final
Summi
  • 36
  • 4