mrodr203 mrodr203 - 1 month ago 8
R Question

Cleaning all columns of Data Frame at once in R

I'm trying to write a line or two of code to
look at every column from a data frame for any blanks
or non-numeric values, such as

N/A
or
NaN
, and replace them with
0
.

Here are some attempts:

Given a data frame=df, with total columns n I tried:

df[,c(1:n)]<-sub("NaN","0",df[,c(1:n)])


And this was an attempt to filter the entire data frame:

df[df[,c(1:n)]=='NaN',"c(1:n)"]


My goal is to do this without using a for loop.

Answer Source

Try df[is.na(df)] <- 0 and df[df == NaN] <- 0