使用data_frame:
Col_1 counts Date_Column
1 23 2015-01-01
2 44 2015-06-11
3 31 2015-07-21
2 22 2015-01-01
我正在使用dplyr包聚合:
aggregated <- data_frame %>% group_by(Col_1,week=week(Date_Column)) %>% summarise_each(funs(sum), -Date_Column)
但我想在函数中包含这个:
collapse_frame <- function(data_frame, group_by_option, minus_option) {
aggregated <- data_frame %>% group_by(group_by_option) %>% summarise_each(funs(sum), -minus_option)
return()
}
但是group_by_option和minus_option没有得到正确的评估。
有没有办法传递这些选项,并在函数内进行评估?
collapse_frame(my_frame, 'Col_1,week=week(Date_Column)', 'Date_Column')
我尝试过使用以下内容:
eval(parse(text=group_by_option))
as.formula(group_by_option)
eval(group_by_option)
答案 0 :(得分:2)
根据@ alistaire的建议:
要分组的列列表:
group_by_list <- list(Col_1, Date_Column)
传递任意帧和列名的方法:
collapse_frame_by_sum <- function(data_frame, group_by_choice, minus_choice) {
collapsed_frame <- data_frame %>% group_by_(.dots=group_by_choice) %>% summarise_each(funs(sum), -eval(parse(text=minus_choice)))
collapsed_frame <- data.frame(collapsed_frame)
return(collapsed_frame)
}
运行方式:
result <- collapse_frame_by_sum(my_frame, group_by_list, 'Date_Column')