Programming in the tidyverse

I'm creating custom ratios and want to clean up my code but having issues to get the mutate section to work.

Below is a simplified version of the problem:

data <- tibble(dep = c("a1", "a1", "a1", "a2", "a2", "a2"), 
             acc = c("a", "b", "c", "a", "b", "d"),
             val = c(10, 20, 30, 21, 31, 41))

# function to create variables (working)
filter_select <- function(.data, ...) {
  .data %>%
    filter(acc %in% c(...)) %>%
    spread(key = acc, value = val)
}

# function to calculate the custom ratio (not working)
ratio <- function(.data, ratio_name, ...) {
  .data %>%
    mutate(
      ratio_name = ratio_name,
      ratio = vars(...))
}

data %>%
  filter_select("a","b") %>%
  ratio("ratio1", a/b)

The original code looks like this:

data %>%
  filter(acc %in% c("a", "b")) %>%
  spread(key = acc, value = val) %>%
  mutate(ratio_name = "ratio1",
         ratio = a / b)

Any help with this will be greatly appreciated.

Dawie

For those who might struggle with the same problem of passing an expression to a function using ... I found the solution at the following link https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Evaluation-of-expression-objects

The solution now looks like this:

ratio <- function(.data, ratio_name, ...){
  .data %>%
    mutate(
      ratio_name = ratio_name,
      ratio = eval(expr( ...)))
}

3 Likes

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