R lapply convert NA's to 0

风格不统一 提交于 2019-12-13 04:53:42

问题


I'm trying to convert a subset of columns from NA's to 0's using the following code. Unfortunately it turns all the cells to 0's.

df1 <- data.frame(id = 1:20, col1 = runif(20), col2 = runif(20), col3 = runif(20))

df1[sample(1:20,5),'col1'] <- NA
df1[sample(1:20,5),'col2'] <- NA
df1[sample(1:20,5),'col3'] <- NA

subset1 <- c('col1','col2','col3')

df1[,subset1] <- as.data.frame(lapply(df1[,subset1], function(x) x[is.na(x)] <- 0))

Any suggestions?


回答1:


Try this simple approach

df1[is.na(df1),] <- 0


来源:https://stackoverflow.com/questions/19848963/r-lapply-convert-nas-to-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!