如何将此 dplyr 语句转换为 R 函数
How can I turn this dplyr statement to an R function
本质上,我想转这个:
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)
)
进入
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)
)
}
但是,它一直作为数据对象而不是可用公式返回。代码有什么错误吗?
在函数内部使用assign
保存数据,paste0
创建名称:
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)
本质上,我想转这个:
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)
)
进入
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)
)
}
但是,它一直作为数据对象而不是可用公式返回。代码有什么错误吗?
在函数内部使用assign
保存数据,paste0
创建名称:
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)