DPLYR过滤器在用户定义的函数中不起作用

时间:2017-08-09 13:14:05

标签: r dplyr tidyverse

我正在尝试创建一个按照a中的值过滤订单Universe的函数 品牌代码列并返回一个明确的订单号列表,用于按订单号的结果列表过滤同一个Universe。

这第二个 过滤宇宙将按品牌代码分组并计算数量 每个品牌代码的出现。

以下是创建示例订单Universe的代码。

library(tidyverse)
library(magrittr)

order_number   <- c("1","1","1","2","2","2","3","3","3","4","4","4")
item_brand_code <- 
c("ab","bb","cb","ab","uy","ik","ab","uy","sq","xx","xy","xz")
orderuniverse<-tibble(order_number,item_brand_code)

以下是创建我正在寻找的结果的代码

orderuniverse %>% 
filter(item_brand_code == "ab")%$%
unique(order_number)%>%  
as_tibble()%$%
###gets unique orders with item_brand_code of interest
filter(orderuniverse, order_number %in% .$value)%>%
group_by(item_brand_code)%>%
summarise(brandcode_count=n())%>%as.tibble%>%
arrange(desc(brandcode_count))
#filters orderuniverse to unique list of order_number with item_brandcode of 
#interest and groups by and counts number of times item_brandcode occurs

导致

     item_brand_code      brandcode_count
              <chr>            <int>
1              ab               3
2              uy               2
3              bb               1
4              cb               1
5              ik               1
6              sq               1

当使用上面的代码创建一个函数时,第二个过滤器在函数内部不起作用。

功能代码

brand_affinity<- function(dt,bcode,odnumber){
       group_by<-enquo(bcode)


       dt %>% 
       filter(bcode == "ab")%$%
       unique(odnumber)%>%  
       as_tibble()%$%
       filter(dt, odnumber %in% .$value)%>%
       group_by(!!group_by)%>%
       summarise(brandcode_count=n())%>%as.tibble%>%
       arrange(desc(brandcode_count))

}

affinity(orderuniverse,orderuniverse$item_brand_code,orderuniverse$order_number)

结果

    item_brand_code      brandcode_count
    <chr>                    <int>
1    ab                        3
2    uy                        2
3    bb                        1
4    cb                        1
5    ik                        1
6    sq                        1
7    xx                        1
8    xy                        1
9    xz                        1

如果order_number列

上没有过滤器,则结果如此

是否有某些方法需要使用过滤功能以及我缺少的功能?

0 个答案:

没有答案