higher-order functions and tidy evaluation

Hello, I'm trying to convert a base R inspired higher-order function that groups and finds the mean or median of a column depending on which sub-function is invoked.

In base R, the following works:

sub_function_1 <- function(df, group_vars, summary_vars) {
  result <- aggregate(df[[summary_vars]], by = df[group_vars], FUN = mean, na.rm = TRUE)
  colnames(result) <- c(group_vars, "mean")
  return(result)
}

sub_function_2 <- function(df, group_vars, summary_vars) {
  result <- aggregate(df[[summary_vars]], by = df[group_vars], FUN = median, na.rm = TRUE)
  colnames(result) <- c(group_vars, "median")
  return(result)
}

main_function <- function(df, group_vars, summary_vars, summary_stat) {
  if (summary_stat == "mean") {
    sub_function_1(df, group_vars, summary_vars)
  } else if (summary_stat == "median") {
    sub_function_2(df, group_vars, summary_vars)
  } else {
    stop("Invalid trigger argument. Use 'mean' or 'median'.")
  }
}

main_function(df = iris, group_vars = "Species", summary_vars = "Petal.Length", summary_stat = "mean")

But it's tidy evaluation "equivalent" doesn't work and I don't understand why.

sub_function_1 <- function(df, group_vars, summary_vars) {
  df %>% 
    group_by({{ group_vars }}) %>% 
    summarize(mean = mean({{ summary_vars }}, na.rm = TRUE))
}

sub_function_2 <- function(df, group_vars, summary_vars) {
  df %>% 
    group_by({{ group_vars }}) %>% 
    summarize(median = median({{ summary_vars }}, na.rm = TRUE))
}

main_function <- function(df, group_vars, summary_vars, summary_stat) {
  if (summary_stat == "mean") {
    sub_function_1(df, group_vars, summary_vars)
  } else if (summary_stat == "median") {
    sub_function_2(df, group_vars, summary_vars)
  } else {
    stop("Invalid trigger argument. Use 'mean' or 'median'.")
  }
}

main_function(df = iris, group_vars = "Species", summary_vars = "Petal.Length", summary_stat = "mean")

Could someone please explain what I'm doing wrong. Thanks!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.