使用 replace_with_na 的作用域变体
为减少用 NA 替换取值时代码的重复,您可以使用 replace_with_na() 的"作用域变体"函数:
replace_with_na_at()replace_with_na_if()replace_with_na_all()
替换条件的语法如下:
~.x == "N/A"
这会替换所有等于 "N/A" 的情况。
~.x %in% c("N/A", "missing", "na", " ")
这会替换所有取值为 "N/A"、"missing"、"na" 或 " " 的情况。
本练习是课程的一部分
在 R 中处理缺失数据
练习说明
对于数据集 pacman,请将相同的特殊缺失值 "N/A"、"missing"、"na" 和 " " 进行替换:
- 在
year、month和day上使用replace_with_na_at()。 - 仅对字符型变量使用
replace_with_na_if()。 - 对所有变量使用
replace_with_na_all()。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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(___, ___, ___, ___))