繁体   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