I have a dataframe:
n <- 50
df <- data.frame(id = seq (1:n),
age = sample(c(20:90), n, rep = TRUE),
sex = sample(c("m", "f"), n, rep = TRUE, prob = c(0.55, 0.45))
)
df[,-1] <- do.call(cbind.data.frame,
lapply(df[,-1], function(x) {
x[sample(c(1:n),floor(n/10))]<-NA
x
})
)
What is the most efficient way to convert all the NAs in the columns age and sex to numeric 0? I don't want a separate column (as is the case with using mutate. Is there a way I can directly change the value in the cell? I can do a for loop and do an ifelse condition, but was wondering if there's a better way.
Thanks!