How to substitute NA by 0 in 20 columns?

前端 未结 4 1862
遥遥无期
遥遥无期 2021-01-02 10:25

I want to substitute NA by 0 in 20 columns. I found this approach for 2 columns, however I guess it\'s not optimal if the number of columns is 20. Is there any alternative a

4条回答
  •  耶瑟儿~
    2021-01-02 10:51

    We can use NAer from qdap to convert the NA to 0. If there are multiple column, loop using lapply.

    library(qdap)
    nm1 <- c('b', 'c', 'e', 'f')
    mydata[nm1] <- lapply(mydata[nm1], NAer)
    mydata
    #  a b c  d e f g d.1
    #1 1 0 0  2 3 4 7   6
    #2 2 g 3 NA 4 5 4   Y
    #3 3 r 4  4 0 t 5   5
    

    Or using dplyr

    library(dplyr)
    mydata %>% 
       mutate_each_(funs(replace(., which(is.na(.)), 0)), nm1)
    #  a b c  d e f g d.1
    #1 1 0 0  2 3 4 7   6
    #2 2 g 3 NA 4 5 4   Y
    #3 3 r 4  4 0 t 5   5
    

提交回复
热议问题