Consider the following function which has 6 arguments that can be passed and have 2^6=32 possible outcomes. This quickly grows to unmanageable numbers as the list of parameters grows.
expl<-function(patt=NULL,yearwise=T,monthwise=F,for_year=NULL,bankwise=T,categ=NULL,df=allst)
The code currently looks something like this (I have pasted only the first few if-then statements to give an idea).
if(!is.null(for_year) && is.null(patt)){
if(bankwise && monthwise)
allst %>% mutate(yr=year(date),mth=month(date,abbr = T)) %>% group_by(yr,mth,bank) %>% summarise(counttx=n(),sumcredit=sum(credit,na.rm = T), sumdebit=sum(debit,na.rm = T)) %>% filter(yr==for_year) else
if(bankwise && !monthwise)
allst %>% mutate(yr=year(date)) %>% group_by(yr,bank) %>% summarise(counttx=n(),sumcredit=sum(credit,na.rm = T), sumdebit=sum(debit,na.rm = T)) %>% filter(yr==for_year) else
if(monthwise && !bankwise)
allst %>% mutate(yr=year(date),mth=month(date,abbr = T)) %>% group_by(yr,mth) %>% summarise(counttx=n(),sumcredit=sum(credit,na.rm = T), sumdebit=sum(debit,na.rm = T)) %>% filter(yr==for_year) else
if(!monthwise && !bankwise) message("You have to select at least one of the two as TRUE: monthwise or bankwise")
} else .....
I am sure there is a better way like using a switch but even switch gets unwieldy. Do we have any package or a better way to handle this growing list of arguments that just need incremental changes in a dplyr pipe?
Aucun commentaire:
Enregistrer un commentaire