使用 replace_with_na 的 scoped 變體
為了在以 NA 取代值時減少重複程式碼,你可以使用 replace_with_na() 的「scoped 變體」:
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" 和 " " 取代為 NA:
- 在
year、month和day使用replace_with_na_at()。 - 僅在字元(character)變數上使用
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(___, ___, ___, ___))