How to substitute NA by 0 in 20 columns?

前端 未结 4 1836
遥遥无期
遥遥无期 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 11:06

    The replace_na function from tidyr can be applied over a vector as well as a dataframe (http://tidyr.tidyverse.org/reference/replace_na.html).

    Use it with a mutate_at variation from dplyr to apply it to multiple columns at the same time:

    my_data %>% mutate_at(vars(b,c,e,f), replace_na, 0)
    

    or

    my_data %>% mutate_at(c('b','c','e','f'), replace_na, 0)
    

提交回复
热议问题