How to replace all NA in a dataframe using tidyr::replace_na? [duplicate]

时光怂恿深爱的人放手 提交于 2019-12-02 22:22:14

If replace_na is not a mandatory requirement, following code will work:

mtcars %>% replace(is.na(.), 0)

Reference Issue: https://stackoverflow.com/a/45574804/8382207

I found a way to get it working with replace_na as requested (as it is the fastest option via microbenchmark testing):

library(tidyr)
library(dplyr)

# First, create a list of all column names and set to 0
myList <- setNames(lapply(vector("list", ncol(mtcars)), function(x) x <- 0), names(mtcars))

# Now use that list in tidyr::replace_na 
mtcars %>% replace_na(myList)

To apply this to your working data frame, be sure to replace the 2 instances of mtcars with whatever you have named your working data frame when creating the myList object.

library(dplyr)
mydata <- mtcars
mydata[sample(1:nrow(mydata), 4), sample(1:ncol(mydata), 4)]<- NA
mydata %>% mutate_each(funs(replace(., is.na(.), 0)))
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!