I'm building a calculator that simplifies an extremely complex calculation.
When vectorizing a function, what is the best way to handle the user leaving out given values?
The goal is to be able to pass it a tibble with a variable assigned per column. I know, from debug suffering, that I should use ifelse() throughout and & instead of && and have recently refactored around that.
In our case below, column c may or may not have entries, as sometimes the value is needed, but when it's not, I want to skip past the more complicated function and use a simpler one.
Sometimes, the column may not exist/will not be passed to the function, and sometimes rows may simply not have the value.
test_cars <- data.frame(weight = c(2500,3000, 4000),
distance = c(300, 450, 400),
tank = c(16, 15, NA))
test_cars2<- data.frame(weight = c(2500,3000, 4000),
distance = c(300, 450, 400))
mileage_calculation <- function( weight, distance, tank_volume=NULL) {
ifelse(exists(weight) & exists(distance) & exists(tank_volume),
gas_mileage(weight,distance, tank_volume),
electric_mileage(weight, distance) )
}
I know that 'exists()' is probably not the way to go, as it'll trip on NULL, which I believe is needed to handle optional inputs. I'm considering '!is.null()', but is there a more effective function to use to check user inputs? What's the best practice to prevent logical mistakes?
Honestly, everything is plug-and-chug based on whether variables are given, or not. Otherwise, it's all base-r computation or flow logic to address the scenarios.