Replacing missing values of factor in a data frame-alternative way for loop-R

时间:2016-04-04 18:46:13

标签: r

I have a data frame(df) with a numeric column and two factor columns as below:

df<-data.frame(x=as.numeric(1:5),
              y=as.factor(c("a","a","b",NA,"b")),
              z=as.factor(c("m",NA,"n","m","m")))

I want to replace missing values(NA) with 0. The below code works well:

for(i in 2:ncol(df)){
  levels(df[[i]])<-c(levels(df[[i]]),0)
  df[[i]][is.na(df[[i]])]<-0
}

However, I wonder, is there another way using apply, lapply, sapply procedures? I will be very glad for any help. Thanks a lot.

1 个答案:

答案 0 :(得分:1)

Using lapply,

 df[-1] <- lapply(df[-1], function(x) {
               levels(x) <- c(levels(x),0)
                replace(x, is.na(x),0)
           })

If we are using recode from car

library(car)
df[-1] <- lapply(df[-1], recode, "NA=0")