使用数字过滤器 [英] Using filter with count

查看:198
本文介绍了使用数字过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 count() helper过滤行。
我想输出的是 map%>%count(StudentID)= 3 的所有行。

例如在下面的df中,它应该取出所有的StudentID为10016和10020的行,因为它们只有2个这样的实例,我想要3个。

  StudentID StudentGender成绩TermName ScaleName TestRITScore 
100 M 9 2010年秋季语言用法217
100 M 10 2011-2012语言用法220
100 M 9 2010年秋季阅读210
10016 M 6 2010年秋季语言用法217
10016 M 6 2010年秋季数学210
10020 F 7 2010年秋季语言用法210
10020 F 7 2010年秋季数学213
10022 F 8 2010年秋季语言使用232
10022 F 9 2011-2012 La语言用法240
10022 F 8 2010年秋季数学242

如果我这样做:

  count(df,StudentID)

那么它只给了我一个2列的df,但我想保留我的df的所有列。这就是为什么我认为我应该使用过滤器。

解决方案

我不认为 count 是你在找什么。试试 n()代替:

  df%>%
group_by(StudentID)%>%
filter(n()== 3)

#源:本地数据框[6 x 6]
#组:StudentID

#StudentID StudentGender成绩TermName ScaleName TestRITScore
#1 100 M 9 2010年秋季语言用法217
#2 100 M 10 2011-2012语言用法220
# 3 100 M 9 2010年秋季阅读210
#4 10022 F 8 2010年秋季语言用途232
#5 10022 F 9 2011-2012语言用法240
#6 10022 F 8 2010年秋季数学242


I'm trying to filter row using the count() helper. What I would like as output are all the rows where the map %>% count(StudentID) = 3.

For instance in the df below, it should take out all the rows with StudentID 10016 and 10020 as they are only 2 instances of these and I want 3.

StudentID StudentGender Grade     TermName      ScaleName TestRITScore
100             M     9    Fall 2010    Language Usage          217
100             M    10    2011-2012    Language Usage          220
100             M     9    Fall 2010    Reading                 210
10016           M     6    Fall 2010    Language Usage          217
10016           M     6    Fall 2010    Mathematics             210
10020           F     7    Fall 2010    Language Usage          210
10020           F     7    Fall 2010    Mathematics             213
10022           F     8    Fall 2010    Language Usage          232
10022           F     9    2011-2012    Language Usage          240
10022           F     8    Fall 2010    Mathematics             242

if I do:

count(df, StudentID)

then it only gives me a df with 2 columns, but I want to keep all the columns of my df. thats's why I think I should use filter.

解决方案

I don't think count is what you looking for. Try n() instead:

df %>% 
  group_by(StudentID) %>%
  filter(n() == 3)

# Source: local data frame [6 x 6]
# Groups: StudentID
# 
#   StudentID StudentGender Grade  TermName      ScaleName TestRITScore
# 1       100             M     9 Fall 2010 Language Usage          217
# 2       100             M    10 2011-2012 Language Usage          220
# 3       100             M     9 Fall 2010 Reading                 210
# 4     10022             F     8 Fall 2010 Language Usage          232
# 5     10022             F     9 2011-2012 Language Usage          240
# 6     10022             F     8 Fall 2010 Mathematics             242

这篇关于使用数字过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆