Using replace_with_na scoped variants
To reduce code repetition when replacing values with NA, use the "scoped variants" of replace_with_na():
replace_with_na_at()replace_with_na_if()replace_with_na_all()
The syntax of replacement looks like this:
~.x == "N/A"
This replaces all cases that are equal to "N/A".
~.x %in% c("N/A", "missing", "na", " ")
Replaces all cases that have "N/A", "missing", "na", or " ".
This exercise is part of the course
Dealing With Missing Data in R
Exercise instructions
For the dataset pacman replace the same special missing values, "N/A", "missing", "na", and " ":
year,month, andday, usingreplace_with_na_at().- Only character variables using
replace_with_na_if(). - All variables using
replace_with_na_all().
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Use `replace_with_na_at()` to replace with NA
replace_with_na_at(pacman,
.vars = c(___, ___, ___),
~.x %in% c(___, ___, ___, ___))
# Use `replace_with_na_if()` to replace with NA the character values using `is.character`
replace_with_na_if(pacman,
.predicate = ___,
~.x %in% c(___, ___, ___, ___))
# Use `replace_with_na_all()` to replace with NA
replace_with_na_all(___, ___ %in% c(___, ___, ___, ___))