I have a somewhat complicated function with many arguments. Without going into too many details - it does some calculations on a data.frame using dplyr and plyr and returns a data.frame with several results columns attached.
I have an argument for the main grouping variable and ... for any additional groups. I use these grouping variables both with dplyr and plyr.
The dplyr bit was pretty straightforward - I used enquo and !! without issue. But I cannot figure out how to use the same principles with plyr.
It works with dplyr.
myfun <- function(data, main_group, ...) {
group <- enquo(main_group)
add_groups <- enquos(...)
data %>%
group_by(!! group, !!! add_groups)
}
mydata <- data.frame(a = 1:3, b = 1:3, c = 1:3, d = 1:3)
myfun(mydata, main_group = a, b, c)
But not with plyr and I need both.
myfun <- function(data, main_group, ...) {
group <- enquo(main_group)
add_groups <- enquos(...)
ddply(data, .(!! group, !!! add_groups), .fun = function(X) { data.frame(result1 = 1, result2 = 1, result3 = 1) })
}
myfun(mydata, main_group = a, b, c)
I suppose it would be easiest if I could use a vector of string variable names in ddply call.
ddply(mydata, c("a", "b", "c"), .fun = function(X) { data.frame(result1 = 1, result2 = 1, result3 = 1) })
But how can I get c("a", "b", "c") within the function if the argument values are a, b, c?
rlang
functions work indplyr
and not inplyr
. Also check the githug page where it states thatplyr
is retired – akrun