Tommy O'Dell
Tommy O'Dell

Reputation: 7109

Recode NAs in multiple dataframe columns

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)

enter image description here

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)

Upvotes: 5

Views: 3986

Answers (2)

Alex Brown
Alex Brown

Reputation: 42902

Using plyr's colwise meta-function makes this easy:

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

Upvotes: 2

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193647

You were very close:

df[is.na(df)] <- 0

Upvotes: 11

Related Questions