0
votes

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?

1
rlang functions work in dplyr and not in plyr. Also check the githug page where it states that plyr is retiredakrun
OK, but if you have a variable name as a string (say "a"), but the function uses unquoted names (a), you can use sym("a") to get a. Is there something that does the reverse so I could use the resulting strings in plyr?M4RT1NK4

1 Answers

0
votes

Please do not use plyr, it is retired and outdated. For similar functionality, please see purrr.

However, I do believe you can use deparse(substitute()) to solve your problem. E.g.,

myfun <- function(data, main_group, ...) {
  group <- deparse(substitute(main_group))
  add_groups <- as.character(as.list(match.call(expand.dots = FALSE)$...))
  ddply(data, c(group, add_groups), .fun = function(X) { data.frame(result1 = 1, result2 = 1, result3 = 1) })
}