Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are different ways to substitute NA values with zeros in an R dataframe. One way is to use the is.na() function to identify the NA values and the [ ] operator to replace them with zeros. Here is an example:

# create an example dataframe with NA values
df <- data.frame(a = c(1, 2, NA, 4), b = c(NA, 6, 7, NA), c = c(8, 9, 10, NA))

# substitute NA with zeros
df[is.na(df)] <- 0

# check the result
df

This should output:

  a b  c
1 1 0  8
2 2 6  9
3 0 7 10
4 4 0  0

Note that in this example, all the NA values in the dataframe have been replaced with zeros. If you only want to replace the NA values in certain columns or rows, you can use indexing or subsetting to select the relevant subset of the dataframe.