screechOwl
screechOwl

Reputation: 28189

R lapply convert NA's to 0

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?

Upvotes: 0

Views: 2310

Answers (1)

Jilber Urbina
Jilber Urbina

Reputation: 61214

Try this simple approach

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

Upvotes: 3

Related Questions