在dplyr和lazyeval中发挥作用

时间:2018-06-20 16:58:12

标签: r dplyr

我想通过使用函数使我的R脚本更漂亮。

我的R脚本:

 library(tidyverse) #contains dplyr
Data <- data.frame(date = rep(as.Date(c('2018-06-18', '2018-06-19', '2018-06-20')), 4),
                   quantity = rep(c(1, 2, 3), each = 4),
                   article =  rep(c('insurance', 'pizza'), 6))

        D <- Data %>%

    select(date, quantity, article) %>%
    filter(str_detect(article,"pizza")) %>%
    group_by_(date) %>%
    summarise(quantity=sum(quantity))

我想做这样的事情。有人可以引导我走上正确的道路吗?

    library(tidyverse) 
    library(lazyeval)

    f <- function(name){
    D <- Data %>%
    select_(~date, ~quantity, ~article) %>%
    filter_(~str_detect(~article,"name")) %>%
    group_by_(~date) %>%
    summarise_(quantity=~sum(quantity))
    return(D) 
    }

谢谢。

2 个答案:

答案 0 :(得分:0)

这行吗?

Data <- data.frame(date = rep(as.Date(c('2018-06-18', '2018-06-19', '2018-06-20')), 4),
                   quantity = rep(c(1, 2, 3), each = 4),
                   article =  rep(c('insurance', 'pizza'), 6)) 

f <- function(name){
  D <- Data %>%
    select(date, quantity, article) %>%
    filter(str_detect(article, name)) %>%
    group_by(date) %>%
    summarize(quantity = sum(quantity))

  return(D)
}

是否有特定的原因使用不赞成使用的功能?

答案 1 :(得分:0)

您可以使用enquoquo_name在tidyeval框架中构建函数

library(tidyverse)

Data <- data.frame(date = rep(as.Date(c('2018-06-18', '2018-06-19', '2018-06-20')), 4),
                   quantity = rep(c(1, 2, 3), each = 4),
                   article =  rep(c('insurance', 'pizza'), 6)) 

daily_sales1 <- function(df, product){

  output <- df %>%
    select(date, quantity, article) %>%
    filter(str_detect(article, product)) %>%
    group_by(date) %>%
    summarise(quantity = sum(quantity, na.rm = TRUE))

  return(output)
}

daily_sales1(Data, 'pizza')
#> # A tibble: 3 x 2
#>   date       quantity
#>   <date>        <dbl>
#> 1 2018-06-18        4
#> 2 2018-06-19        3
#> 3 2018-06-20        5

daily_sales2 <- function(df, product){

  product <- enquo(product)

  output <- df %>%
    select(date, quantity, article) %>%
    filter(str_detect(article, !! quo_name(product))) %>%
    group_by(date) %>%
    summarise(quantity = sum(quantity, na.rm = TRUE))

  return(output)
}

daily_sales2(Data, pizza)
#> # A tibble: 3 x 2
#>   date       quantity
#>   <date>        <dbl>
#> 1 2018-06-18        4
#> 2 2018-06-19        3
#> 3 2018-06-20        5

reprex package(v0.2.0)于2018-06-20创建。