Recode NA in multiple data columns

I have several integer columns in a data frame, all with NA, which I need to transcode 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)

Creating such an output ... (only the first few columns of 55)

enter image description here

I can recode NAs to 0 manually, as df$col[is.na(df$col)] <- 0for each column, but given that there are so many columns, it will take some time to print everything.

How can I recode all of these NA to 0 in a string or three?

(I understand that I can melt whole columns and then re-encode one molten column, but I would rather do it in the R base)

+5
source share
2 answers

You were very close:

df[is.na(df)] <- 0
+11
source

- plyr colwise :

dfZ=colwise(function(x)ifelse(is.na(x),0,x))(df)
+2

All Articles