本文介绍了筛选分组变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框:

df <- data.frame(
          Group=c('A','A','A','B','B','B'),
          Activity = c('Act1','Act4', 'Act3','Act1', 'Act2','Act3')
        )

我只想过滤那些同时包含两个活动 Act1 Act2 。以下代码返回零值:

I want to filter for those groups only which contain both activities Act1 and Act2. The following code returns zero values:

df %>% group_by(Group) %>% filter(Activity == 'Act1' & Activity == 'Act2')

如果我使用 df %>%group_by(Group)%>%filter(Activity%in%c('Act1','Act2')),它还会返回我不需要的A组。

If I use df %>% group_by(Group) %>% filter(Activity %in% c('Act1' , 'Act2') ), it also returns group A, which I don't need.

我如何仅获取那些必须包含两者活动的组?

How can I get only those groups that necessarily contain both the activities?

推荐答案

您需要将其包装 any

library(dplyr)
df %>% 
  group_by(Group) %>% 
  filter(any(Activity == 'Act1')  & any(Activity == 'Act2'))

# Group Activity
#  <fct> <fct>   
#1 B     Act1    
#2 B     Act2    
#3 B     Act3 

在基本R选项 ave

df[as.logical(ave(df$Activity, df$Group, 
              FUN = function(x) any(x == 'Act1')  & any(x == 'Act2'))), ]






您可以使用<$ c $获得相同的结果c>全部

df %>% 
  group_by(Group) %>% 
  filter(all(c("Act1", "Act2") %in% Activity))

并与 ave

df[as.logical(ave(df$Activity, df$Group, 
           FUN = function(x) all(c("Act1", "Act2") %in% x))),]


# Group Activity
#4     B     Act1
#5     B     Act2
#6     B     Act3

这篇关于筛选分组变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 14:13