# How To Replace na Values with Zeros In R Dataframe

Let us create a random data for this example.

Below will create a dataframe with 5 columns and 5 rows.

In :
df <- data.frame(matrix(NA, nrow = 5, ncol = 5))

In :
head(df,1)

A data.frame: 1 × 5
X1X2X3X4X5
<lgl><lgl><lgl><lgl><lgl>
1NANANANANA

To replace na values, we can use is.na() function as shown below.

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


Let check our dataframe now.

In :
head(df)

A data.frame: 5 × 5
X1X2X3X4X5
<dbl><dbl><dbl><dbl><dbl>
100000
200000
300000
400000
500000

Ok now we have all the values replaced with zeros.

## Replace na with zeros in a column of Dataframe in R

Let us recreate our dataframe with na values.

In :
df <- data.frame(matrix(NA, nrow = 5, ncol = 5))


For example- replace na in 3rd column with all zeros.

In :
df[,3] <- 0

In :
df

A data.frame: 5 × 5
X1X2X3X4X5
<lgl><lgl><dbl><lgl><lgl>
NANA0NANA
NANA0NANA
NANA0NANA
NANA0NANA
NANA0NANA

## Replace na with zeros in a row of Dataframe in R

For example - replace na in ist row with all zeros.

In :
df[1,] <-0

In :
df

A data.frame: 5 × 5
X1X2X3X4X5
<dbl><dbl><dbl><dbl><dbl>
0 00 0 0
NANA0NANA
NANA0NANA
NANA0NANA
NANA0NANA