给定一列日期,这将计算每个月的记录数
library(dplyr)
library(lubridate)
samp <- tbl_df(seq.Date(as.Date("2017-01-01"), as.Date("2017-12-01"), by="day"))
freq <- samp %>%
filter(!is.na(value)) %>%
transmute(month = floor_date(value, "month")) %>%
group_by(month) %>% summarise(adds = n())
freq
# A tibble: 12 x 2
month adds
<date> <int>
1 2017-01-01 31
2 2017-02-01 28
3 2017-03-01 31
4 2017-04-01 30
5 2017-05-01 31
6 2017-06-01 30
7 2017-07-01 31
8 2017-08-01 31
9 2017-09-01 30
10 2017-10-01 31
11 2017-11-01 30
12 2017-12-01 1
>
我想将其转换为函数,以便我可以对多个变量执行操作。已阅读有关 dplyr 编程的小插图,但仍然存在问题。
我的尝试;
library(rlang)
count_x_month <- function(df, var, name){
var <- enquo(var)
name <- enquo(name)
df %>%
filter(!is.na(!!var)) %>%
transmute(month := floor_date(!!var, "month")) %>%
group_by(month) %>% summarise(!!name := n())
}
freq2 <- samp %>% count_x_month(value, out)
错误信息;
Error: invalid argument type
使这个版本的功能正常工作将会有很大的帮助。更广泛地说,实现这一目标的其他方式也将受到欢迎。 陈述问题的一种方式;给定客户数据框和首次购买日期,计算每个月首次购买的客户数量。
更新:所选答案适用于 dplyr 0.7.4,但我有权访问的 rstudio 环境具有 dplyr 0.5.0。需要进行哪些修改才能“向后移植”此函数?
最佳答案
您忘记quo_name
它
library(rlang)
count_x_month <- function(df, var, name){
var <- enquo(var)
name <- enquo(name)
name <- quo_name(name)
df %>%
filter(!is.na(!!var)) %>%
transmute(month := floor_date(!!var, "month")) %>%
group_by(month) %>%
summarise(!!name := n())
}
freq2 <- samp %>% count_x_month(value, out)
# A tibble: 12 x 2
month out
<date> <int>
1 2017-01-01 31
2 2017-02-01 28
3 2017-03-01 31
4 2017-04-01 30
5 2017-05-01 31
6 2017-06-01 30
7 2017-07-01 31
8 2017-08-01 31
9 2017-09-01 30
10 2017-10-01 31
11 2017-11-01 30
12 2017-12-01 1
参见“Programming with dplyr”的“不同的输入和输出变量”部分:
We create the new names by pasting together strings, so we need quo_name() to convert the input expression to a string.
关于r - 将 dplyr 链转换为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47896101/