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