首页 文章

具有多个条件的重复过滤,无需循环

提问于
浏览
0

我有一个大约35000个观测值和24个变量(其中一个是时间序列)的大型数据集,但我可以总结一下我想用虹膜实现的目标 .

library(tidyverse)

iris.new <- iris %>%
  arrange(Species, Sepal.Length, Sepal.Width) %>%
  group_by(Species)

unwanted <- iris.new %>%
  filter(Sepal.Length > 5 & Sepal.Width==min(Sepal.Width))

while(nrow(unwanted)!=0) {
  iris.new <- iris.new %>%
    arrange(Species, Sepal.Length, Sepal.Width) %>%
    group_by(Species) %>%
    filter(!(Sepal.Length > 5 & Sepal.Width == min(Sepal.Width)))
  unwanted <- iris.new %>%
    filter(Sepal.Length > 5 & Sepal.Width==min(Sepal.Width))
}

我想只过滤Sepal.Length> 5,它具有最小的Sepal.Width观察范围内的每个物种(setosa和versicolor没有) . 当我摆脱第一个,我重复过滤器,看看是否有任何,并最终使用'while'循环为我这样做 .

有没有办法在不使用循环的情况下过滤它们?

1 回答

  • 0

    我认为这样做的诀窍:

    # get minimum Sepal.Width without Sepal.Length > 5
    iris_min <- iris %>%
      group_by(Species) %>%
      filter(Sepal.Length <= 5) %>%
      summarize(min_sep_width = min(Sepal.Width))
    
    # check to see that nothing is below our minimum 
    #   or equal to it with a Sepal.Length that's too long
    iris_new <- iris %>% 
      left_join(iris_min, by = c('Species')) %>%
      filter(min_sep_width < Sepal.Width | 
               (min_sep_width == Sepal.Width & Sepal.Length <= 5)) %>%
      select(-min_sep_width)
    

相关问题