简体   繁体   中英

Conditional filtering based on the level of a factor R

I would like to clean up the following code. Specifically, I'm wondering if I can consolidate the three filter statements so that I end up with the final data.frame (the rind()) that contains the row of data "spring" if it exists, the row of data for "fall" if "spring" doesn't exist, and finally the row of data if neither "spring" nor "fall" exist. The code below seems very clunky and inefficient. I am trying to free myself of for(), so hopefully the solution won't involve one. Could this be done using 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)

It looks like within each group of f , you want to extract the row of, in descending order of preference, spring , fall , or other .

If you first make your ordering of preference the actual factor ordering:

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

Then you can use this dplyr solution to get the minimum row (relative to that factor) within each group:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM