精華區beta R_Language 關於我們 聯絡資訊
如何用 dplyr 移除特定條件的 row (有NA的情況) ex: ID <- c(1:10) VAL <- c(1,2,3,NA,5,6,7,NA,9,10) data <- data.frame(ID, VAL, stringsAsFactors=F) ### 如果我不要5以下的 我不能寫 data %>% filter(VAL >= 6) 會沒有 NA 也許可以改成 data %>% filter(VAL >= 6 & is.na(VAL)) 可是萬一資料有其他的東西 例如空格, 小老鼠之類的? 有沒有什麼辦法是 "選到符合條件的, 然後移除那些row" ? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.109.73.102 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1451892093.A.521.html
cywhale: 如果寫 data[-which(VAL <= 5),] 符合你所要的嗎? 01/04 15:47
celestialgod: setdiff(data, data %>% filter(VAL < 6)) 01/04 16:07
celestialgod: data %>% setdiff(filter(., VAL < 6)) 01/04 16:12
celestialgod: setdiff後來dplyr有新增方法使用於data.frame 01/04 16:13
memphis: HI cywhale 根據經驗, 那樣寫如果which=0, 資料會爆掉喔 01/04 16:15
memphis: 要先 s <- which(VAL <= 5) 再判斷 if(!is.na(s[1])) 01/04 16:16
celestialgod: 疑問,為啥which會出現0? 01/04 16:21
celestialgod: which(data$VAL <= 5) 應該只會出現1~nrow(data)吧 01/04 16:21
memphis: 喔喔 感恩~ c大正解, 這樣寫起來就很dplyr style 01/04 16:22
memphis: 如果資料裡沒有<=5的 就會選空, 結果等於 integer(0) 01/04 16:23
memphis: 所以一般過which 我都會塞到一個s 然後判斷有沒有東西 01/04 16:25
celestialgod: 喔喔 你說NULL喔,我懂了!! 01/04 16:28
celestialgod: 我在想0是什麼XDD 01/04 16:28
celestialgod: setdiff配上%>%是真的滿dplyr style XD 01/04 16:29
memphis: 補充: 可是c大的方法好看, 速度非常慢 因為是df的setdiff 01/04 16:59
cywhale: ya 我忘記null這狀況,通常我也都會加個判斷式再做.. 01/04 17:00
memphis: data %>% slice(setdiff(1:nrow(.),which(VAL<6))) 01/04 17:03
memphis: 上面這個讓setdiff回到比兩個vector, 只是看起來就醜點 01/04 17:04
celestialgod: 我原本要貼這個XD:http://pastebin.com/P468HC0L 01/04 17:40
celestialgod: 不過看到cy大用-which就想說算了~~ 01/04 17:40
celestialgod: 原來有差異的QQ 01/04 17:42
cywhale: If original column contains "@" as memphis said 01/04 21:28
cywhale: then the column become character, and these solutions 01/04 21:29
cywhale: will differ from data[-which(VAL<=5),] for VAL='10' 01/04 21:30