简体   繁体   English

自定义 function 中的条件变异以更改 R 中的字符列

[英]Conditional mutate in a custom function to change a character column in R

Suppose I have the following function in R:假设我在 R 中有以下 function:

my_function <- function(date1, date2, variable, quota, monthly_business_days) {
    my_data %>%
        filter(between(DATE, ymd(date1), ymd(date2))) %>% 
        summarize(total = sum({{variable}})) %>%
        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).根据“变量”上的输入,它指的是“my_data”dataframe 中的列,我想以不同的方式进行(参见 if/else 块)。 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).但是,用 dplyr 是不可能做到这一点的(唯一的选择是单独编写所有内容,但我不能写那么多行代码)。 I'm currently working in a Shiny Application trying to reduce the lines of code with the use of functional programming.我目前在 Shiny 应用程序中工作,试图通过使用函数式编程来减少代码行。

Different posts here on StackOverflow have not given me the answer so far.到目前为止,StackOverflow 上的不同帖子还没有给我答案。

I would really appreciate any help.我真的很感激任何帮助。 Thanks!谢谢!

Try using the below function:尝试使用以下 function:

library(dplyr)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM