I have a function that takes gross income as input and gives me the net income as output:
gross_net <- function(gross_income,
social_security = 0.2,
tax = 0.3){
net_income <- (gross_income - gross_income * social_security) * (1 - tax)
net_income
}
gross_net(2000)
> gross_net(2000)
[1] 1120
I am looking for some kind of iteration that - if I only have a net income value - "tries out" several gross income values in the gross_net function until it picks the right gross income value that corresponds to the net income value. (I know it would probably be faster to invert the function.)
I thought of a while loop that has a lower and upper parameter (e.g. the gross income values that are tried out must lie between 1.1 times the net_income and 2 times the net_income). It should check if gross_net(net_income * upper) is higher than my net_income, if it is higher then try gross_net(net_income * lower). If this is lower than my net_income the try a value a little smaller than the original upper parameter and so on until the gross income value that corresponds to the provided net income value is reached (or until the gross income value is in a certain range).
I tried something like
net_gross <- function(income){
test_net_income <- income
upper <- 2
lower <- 1.1
while(test_income != gross_net(test_net_income)){
if(gross_net(test_net_income * upper) > income)
upper <- lower + (upper - lower) * 0.9
test_income <- income * lower
if(gross_net(test_net_income * lower) > income)
lower <- upper - (upper - lower) * 0.9
test_income <- income * upper
}}
but obviously that does not work. Is a while loop even the "right" way to do this? (I explicitly need a solution involving iteration - inverting the function is not an option for me.)