# Convert NA to 0 in a numeric vector
convert_na_to(
c(9, 3, NA, 2, 3, 1, NA, 8),
replacement = 0
)
# Convert NA to "missing" in a character vector
convert_na_to(
c("a", NA, "d", "z", NA, "t"),
replacement = "missing"
)
### For data frames
test_df <- data.frame(
x = c(1, 2, NA),
x2 = c(4, 5, NA),
y = c("a", "b", NA)
)
# Convert all NA to 0 in numeric variables, and all NA to "missing" in
# character variables
convert_na_to(
test_df,
replace_num = 0,
replace_char = "missing"
)
# Convert a specific variable in the data frame
convert_na_to(
test_df,
replace_num = 0,
replace_char = "missing",
select = "x"
)
# Convert all variables starting with "x"
convert_na_to(
test_df,
replace_num = 0,
replace_char = "missing",
select = starts_with("x")
)
# Convert NA to 1 in variable 'x2' and to 0 in all other numeric
# variables
convert_na_to(
test_df,
replace_num = 0,
select = list(x2 = 1)
)
Run the code above in your browser using DataLab