作者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/cn.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