Expectations_of_life <- function(g, x, e) { if (g == "m") { termination_age = 102 - x } else if (g == "f") { termination_age = 105 - x } Life_function <- function(x) { if (g == "m") { return(1000 * (1 - (x / 102))) } else if (g == "f") { return(1000 * (1 - (x / 105))) } } if (e == "curtate") { years <- 1:termination_age return(sum(Life_function(x + years) / Life_function(x))) } else if (e == "complete") { func <- function(t) { return(Life_function(x + t) / Life_function(x)) } return(integrate(func, 0, termination_age)$value) } } check <- Expectations_of_life("f", 43, "curtate") print(check)