r replace na with 0

# Create a sample dataframe
df <- data.frame(
  A = c(1, 2, NA, 4, 5),
  B = c(NA, 3, 4, NA, 6)
)

# Replace NA values with 0 in the dataframe
df[is.na(df)] <- 0

Explanation:

  1. Creation of a sample dataframe df with two columns 'A' and 'B'.
  2. The is.na() function identifies NA (missing) values within the dataframe.
  3. The assignment operator <- along with indexing df[is.na(df)] is used to select the NA values within the dataframe.
  4. The selected NA values are replaced with 0 using the assignment <- 0.