簡體   English   中英

基於因子R的級別的條件過濾

[英]Conditional filtering based on the level of a factor R

我想清理以下代碼。 具體來說,我想知道我是否可以合並三個過濾語句,以便最終得到最終的data.frame(rind()),其中包含數據行“spring”(如果存在),數據行為“如果“春天”不存在,最后如果既不存在“春天”也不存在“秋天”,那么數據行就會存在。 下面的代碼看起來非常笨重和低效。 我試圖讓自己為(),所以希望解決方案不會涉及一個。 這可以使用dplyr完成嗎?

# define a %not% to be the opposite of %in%
library(dplyr)
`%not%` <- Negate(`%in%`)
f <- c("a","a","a","b","b","c")
s <- c("fall","spring","other", "fall", "other", "other")
v <- c(3,5,1,4,5,2)
(dat0 <- data.frame(f, s, v))
sp.tmp <- filter(dat0, s == "spring")
fl.tmp <- filter(dat0, f %not% sp.tmp$f, s == "fall")
ot.tmp <- filter(dat0, f %not% sp.tmp$f, f %not% fl.tmp$f, s == "other")
rbind(sp.tmp,fl.tmp,ot.tmp)

看起來在每組f ,你想要按照偏好, springfallother降序來提取行。

如果您首先按優先順序排列實際因素排序:

dat0$s <- factor(dat0$s, levels=c("spring", "fall", "other"))

然后,您可以使用此dplyr解決方案獲取每個組中的最小行(相對於該因子):

newdat <- dat0 %.% group_by(f) %.% filter(rank(s) == 1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM