I have multiple integer columns in a data frame, all with NAs that I need to recode to 0.
df1 <- as.data.frame(sapply(paste(sample(letters,50,T),sample(letters,10), sep=""), function(x) {sample(c(NA,0:5),10,T)} ))
df2 <- as.data.frame(sapply(paste(sample(letters,5,T),sample(letters,10,T), sep=""), function(x) {sample(letters[1:5],10,T)} ))
df <- cbind(df2,df1)
Producing an output like this... (only the first few columns of the 55 shown)
I can go about recoding the NAs to 0 manually like df$col[is.na(df$col)] <- 0
for each column, but given that there are so many columns, it would take a while to type that all out.
How can I recode all of these NAs to 0 in a line or three?
(I realise I could melt the integer columns and then recode the one melted column, but I'd rather do this in base R)
You were very close:
df[is.na(df)] <- 0
Using plyr
's colwise
meta-function makes this easy:
dfZ=colwise(function(x)ifelse(is.na(x),0,x))(df)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With