作者memphis (讓你喜歡這世界~)
看板R_Language
標題[問題] dplyr 移除特定條件
時間Mon Jan 4 15:21:30 2016
如何用 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://webptt.com/m.aspx?n=bbs/R_Language/M.1451892093.A.521.html
1F:→ cywhale: 如果寫 data[-which(VAL <= 5),] 符合你所要的嗎? 01/04 15:47
2F:→ celestialgod: setdiff(data, data %>% filter(VAL < 6)) 01/04 16:07
3F:→ celestialgod: data %>% setdiff(filter(., VAL < 6)) 01/04 16:12
4F:→ celestialgod: setdiff後來dplyr有新增方法使用於data.frame 01/04 16:13
5F:→ memphis: HI cywhale 根據經驗, 那樣寫如果which=0, 資料會爆掉喔 01/04 16:15
6F:→ memphis: 要先 s <- which(VAL <= 5) 再判斷 if(!is.na(s[1])) 01/04 16:16
7F:→ celestialgod: 疑問,為啥which會出現0? 01/04 16:21
8F:→ celestialgod: which(data$VAL <= 5) 應該只會出現1~nrow(data)吧 01/04 16:21
9F:→ memphis: 喔喔 感恩~ c大正解, 這樣寫起來就很dplyr style 01/04 16:22
10F:→ memphis: 如果資料裡沒有<=5的 就會選空, 結果等於 integer(0) 01/04 16:23
11F:→ memphis: 所以一般過which 我都會塞到一個s 然後判斷有沒有東西 01/04 16:25
12F:→ celestialgod: 喔喔 你說NULL喔,我懂了!! 01/04 16:28
13F:→ celestialgod: 我在想0是什麼XDD 01/04 16:28
14F:→ celestialgod: setdiff配上%>%是真的滿dplyr style XD 01/04 16:29
15F:→ memphis: 補充: 可是c大的方法好看, 速度非常慢 因為是df的setdiff 01/04 16:59
16F:推 cywhale: ya 我忘記null這狀況,通常我也都會加個判斷式再做.. 01/04 17:00
17F:→ memphis: data %>% slice(setdiff(1:nrow(.),which(VAL<6))) 01/04 17:03
18F:→ memphis: 上面這個讓setdiff回到比兩個vector, 只是看起來就醜點 01/04 17:04
20F:→ celestialgod: 不過看到cy大用-which就想說算了~~ 01/04 17:40
21F:→ celestialgod: 原來有差異的QQ 01/04 17:42
22F:推 cywhale: If original column contains "@" as memphis said 01/04 21:28
23F:→ cywhale: then the column become character, and these solutions 01/04 21:29
24F:→ cywhale: will differ from data[-which(VAL<=5),] for VAL='10' 01/04 21:30