简体   繁体   中英

How can I turn this dplyr statement to an R function

Essentially, I want to turn this:

sum_user_daily_p1 <- raw_user_daily_agg %>%
group_by(UserID) %>%
filter(ProductID == 1) %>%
summarize(
  LOR_months = (difftime(max(Date), min(Date), units = "weeks")),
  bets_total = sum(Bets),
  max_bet = max(Bets),
  min_bet = min(Bets)
)

....

sum_user_daily_p8 <- raw_user_daily_agg %>%
group_by(UserID) %>%
filter(ProductID == 8) %>%
summarize(
  LOR_months = (difftime(max(Date), min(Date), units = "weeks")),
  bets_total = sum(Bets),
  max_bet = max(Bets),
  min_bet = min(Bets)
)

into

sum_by_p <- function(x) {

name <- c('sum_user_daily_p', x)

  name <- raw_user_daily_agg %>%
    group_by(UserID) %>%
    filter(ProductID == x) %>%
    summarize(
      LOR_months = (difftime(max(Date), min(Date), units = "weeks")),
      bets_total = sum(Bets),
      max_bet = max(Bets),
      min_bet = min(Bets)
    )
}

However, it keeps being returned as a data object instead of a usable formula. Is there some error in the code?

Use assign inside the function to save the data and paste0 to create the name:

sum_by_p <- function(data, x) {

  name <- paste0('sum_user_daily_p', x)

  data <- data %>%
    group_by(UserID) %>%
    filter(ProductID == x) %>%
    summarize(
      LOR_months = (difftime(max(Date), min(Date), units = "weeks")),
      bets_total = sum(Bets),
      max_bet = max(Bets),
      min_bet = min(Bets)
    )
  assign(name, data, envir=globalenv()) # to create name in the global env.
}

sum_by_p(raw_user_daily_agg, x=1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM