dplyr中的函數內借鑒許多資料庫操作的函數而來,這邊要分享的一對函數便是這種關係,我們常見一個情況需要將資料中的NA取代成特定得值,或是將某些值當作NA處理,這邊在R dplyr中的coalesce和na_if便是很好的幫手,coalesce函數就是直接借來在SQL中同名的函數名稱在這邊使用,他的功能也是用來做NA取代,放入估計的函數,這邊便來釋放一些例子:
coalesce
coalesce接受vector,然後將第一個遇到的NA值取代成為特定的數值,要發揮它最大的效果可以跟purrr函數的map一起使用,便能大幅增加他的適用性。
# Use a single value to replace all missing values x <- sample(c(1:5, NA, NA, NA)) coalesce(x, 0L) # Or match together a complete vector from missing pieces y <- c(1, 2, NA, NA, 5) z <- c(NA, NA, 3, 4, 5) coalesce(y, z)
na_if
na_if(x, y)剛好跟coalesce相反,輸入的vector x中,只要跟vector y中相等的就會被替換變成NA值。
na_if(1:5, 5:1) x <- c(1, -1, 0, 10) 100 / x 100 / na_if(x, 0) y <- c("abc", "def", "", "ghi") na_if(y, "")