问题
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