基于因子R水平的条件过滤
我想清理以下代码。具体地说,我想知道是否可以合并这三个filter语句,从而得到最终的data.frame(rind()),其中包含数据行“spring”(如果存在),数据行“fall”(如果“spring”不存在),最后是数据行(如果“spring”和“fall”都不存在)。下面的代码看起来非常笨拙和低效。我正在尝试将自己从for()中解放出来,因此希望解决方案不会涉及for()。这可以用dplyr来完成吗基于因子R水平的条件过滤,r,dplyr,R,Dplyr,我想清理以下代码。具体地说,我想知道是否可以合并这三个filter语句,从而得到最终的data.frame(rind()),其中包含数据行“spring”(如果存在),数据行“fall”(如果“spring”不存在),最后是数据行(如果“spring”和“fall”都不存在)。下面的代码看起来非常笨拙和低效。我正在尝试将自己从for()中解放出来,因此希望解决方案不会涉及for()。这可以用dplyr来完成吗 # define a %not% to be the opposite of %in%
# 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)
#将%not%定义为%in%的对立面
图书馆(dplyr)
`%不是%`看起来在f
的每组中,您希望按首选项的降序提取spring
、fall
或other
的行
如果您首先将偏好排序作为实际因子排序:
dat0$s <- factor(dat0$s, levels=c("spring", "fall", "other"))
dat0$s一个“a”、“b”或“c”中是否可能有多个“spring”?如果是,你想保留所有的还是只保留第一个?不可能有多个“spring”来表示“a”,“b”…谢谢,这正是我想要的。
newdat <- dat0 %.% group_by(f) %.% filter(rank(s) == 1)