lundi 14 décembre 2020

Conditional mutate in a custom function to change a character column in R

Suppose I have the following function in R:

my_function <- function(date1, date2, variable, quota, monthly_business_days) {
    my_data %>%
        filter(between(DATE, ymd(date1), ymd(date2))) %>% 
        summarize(total = sum()) %>%
        add_row(total = quota, .before = 1) %>% 
        rbind(.$total[[2]]/bizdays(date1, date2)*monthly_business_days)
    if(variable == UNITS) { 
        %>% mutate(indicator = c("Quota (Units)", "Sales (Units)", "Forecast (Units)"))
    } else {
        %>% mutate(indicator = c("Quota (USD)", "Sales (USD)", "Forecast (USD)"))
    }
}

Depending on the input on "variable", which refer to columns in "my_data" dataframe, I would like to proceed in different ways (see the if/else chunk). However, it is not possible to do this with dplyr (the only option would be writing everything separately, but I cannot afford to write that many lines of code). I'm currently working in a Shiny Application trying to reduce the lines of code with the use of functional programming.

Different posts here on StackOverflow have not given me the answer so far.

I would really appreciate any help. Thanks!

Aucun commentaire:

Enregistrer un commentaire