使用r(dplyr)中的一组值进行过滤 [英] Filtering with a set of values in r (dplyr)

查看:48
本文介绍了使用r(dplyr)中的一组值进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用 R 中的 dplyr 包进行过滤有疑问.

I have a question regarding filtering using the dplyr package in R.

我有一个当前的数据框,如下所示:

I have a current dataframe as follows:

  url                       season    salary
   <fct>                     <fct>      <dbl>
 1 /players/a/abrinal01.html 2016-17  5725000
 2 /players/a/ackeral01.html 2008-09   711517
 3 /players/a/acyqu01.html   2012-13   788872
 4 /players/a/acyqu01.html   2013-14   915243
 5 /players/a/acyqu01.html   2014-15   981348
 6 /players/a/acyqu01.html   2015-16  1914544
 7 /players/a/acyqu01.html   2016-17  1709538
 8 /players/a/adamsjo01.html 2014-15  1404600
 9 /players/a/adamsst01.html 2014-15  3140517
10 /players/a/adamsst01.html 2016-17 22471910
11 /players/a/adamsst01.html 2017-18 2571910

我想按URL分组,仅保留那些包含仅在2012-2013、2013-2014和2014-2015赛季播放过的URL的行.

I would like to group by URL and only keep those rows which contain URLs that played in seasons 2012-2013, 2013-2014 and 2014-2015 only.

我已经尝试过了,但是它给出了一个错误:

I have tried this, but it gives an error :

filter_impl(.data,quo)中的错误:结果的长度必须为1,而不是3

Error in filter_impl(.data, quo) : Result must have length 1, not 3

p_filter <- p_g_stagger %>% 
  dplyr :: group_by(url) %>%
  dplyr :: filter(season == c('2012-13', '2013-14', '2014-15'))

我想要的输出是这样

       url                       season    salary
       <fct>                     <fct>      <dbl>
     1 /players/a/acyqu01.html   2012-13   788872
     2 /players/a/acyqu01.html   2013-14   915243
     3 /players/a/acyqu01.html   2014-15   981348

推荐答案

我们在 filter

1)仅过滤具有 season_needed

2)仅过滤条件1中那些选定组中的 season_needed .

2) Filters only the season_needed from those selected groups in condition 1.

season_needed <- c('2012-13', '2013-14', '2014-15')
library(dplyr)

df %>%
  group_by(url) %>%
  filter(all(season_needed %in% season) & season %in% season_needed)

#  url                     season  salary
#  <fct>                   <fct>    <int>
#1 /players/a/acyqu01.html 2012-13 788872
#2 /players/a/acyqu01.html 2013-14 915243
#3 /players/a/acyqu01.html 2014-15 981348

这篇关于使用r(dplyr)中的一组值进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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