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:
- Creation of a sample dataframe
df
with two columns 'A' and 'B'. - The
is.na()
function identifies NA (missing) values within the dataframe. - The assignment operator
<-
along with indexingdf[is.na(df)]
is used to select the NA values within the dataframe. - The selected NA values are replaced with 0 using the assignment
<- 0
.