R语言 按另一列中的两个条件过滤数据框中的列

qhhrdooz  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(143)

假设我们有这样的东西

df <- data.frame(species = c("Passer", "Turdus", "Turdus", "Gallus", "Anas", "Anas"),
                 season = c("breeding", "breeding", "non-breeding", "non-breeding", "breeding", "non-breeding"), 
                 value = seq(1, 12, 2), 
                 drop = c("no", "no", "dog", "dog", "cat", "cat"))
species       season value drop
1  Passer     breeding     1   no
2  Turdus     breeding     3   no
3  Turdus non-breeding     5  dog
4  Gallus non-breeding     7  dog
5    Anas     breeding     9  cat
6    Anas non-breeding    11  cat

我想选择具有繁殖季节两个值的物种的行,即繁殖和非繁殖。
结果应如下所示

species       season value drop
2  Turdus     breeding     3   no
3  Turdus non-breeding     5  dog
5    Anas     breeding     9  cat
6    Anas non-breeding    11  cat

我用filter()试了几次,但是我不能让它工作。我怀疑做一个循环可能是一种方法?谢谢!

h6my8fg2

h6my8fg21#

如果有恰好物种出现两次的可能性,就可以这样使用:

library(dplyr)

 df %>% 
   add_count(species) %>% 
   filter(n == 2) %>% 
   select(-n)

  species       season value drop
1  Turdus     breeding     3   no
2  Turdus non-breeding     5  dog
3    Anas     breeding     9  cat
4    Anas non-breeding    11  cat

另一种方法是

df %>% 
  group_by(species) %>% 
  filter(nlevels(factor(season)) == 2)

相关问题