Conditional filtering based on the level of a factor R

后端 未结 1 908
我寻月下人不归
我寻月下人不归 2021-01-16 12:20

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 ri

1条回答
  •  遥遥无期
    2021-01-16 12:30

    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)
    

    0 讨论(0)
提交回复
热议问题