The function was written to accept scalar arguments but you can vectorize it like this:
Vectorize(ub_duration)(25, c(12, 18, 24), dur = 0)
## [1] 150 210 330
or use sapply
:
sapply(c(12, 18, 24), ub_duration, age = 25, dur = 0)
## [1] 150 210 330
Note that dur
, cc_lag
and extended
are arguments that are not used in the body of the function shown in the question. Even if dur
is passed it is immediately overwritten with NULL in the first if
statement if that statement returns. Also, cc_lag
and extended
are not referenced at all. Perhaps you intended that the dur
argument is the default if the ages are between 40 and 50 since those ages are not otherwise handled but in fact it returns NULL in that case. The function itself needs to be fixed depending on what you want and that was not described in the question.
Rewriting Function
1) Here is an attempt at rewriting it. First create an m
matrix with the cutoff values. The rows correspond to cc
and the columns to age
. Ensure that cc
and age
are the same length by putting them into a data frame and extracting them back out. Then compute the indexes into m
for cc
and age
. Note that it is possible that an age
does not correspond to any index so in that case set its index to NA. If that is the case return dur
and otherwise return the value looked up in m
.
ub_duration2 <- function(age, cc, dur = 0) {
m <- matrix(c(150, 210, 310,
180, 330, 420,
270, 400, 540), 3, dimnames = list(cc = 1:3, age = 1:3))
d <- data.frame(age, cc)
age <- d$age
cc <- d$cc
cc.ix <- 1 + (cc >= 15) + (cc >= 24)
age.ix <- 1 * (age < 30) + 2 * (age >= 30 & age < 40) + 3 * (age > 50)
age.ix[age.ix == 0] <- NA
ifelse(is.na(age.ix), dur, m[cbind(cc.ix, age.ix)])
}
ub_duration2(25,c(12, 18, 24))
## [1] 150 210 310
2) This attempt is closer in spirit to what you have in the question. It works on scalars and then we use Vectorize
to vectorize it. Although tedious it may be preferred in terms of simplicity.
ub_duration_scalar <- function(age, cc, dur = 0) {
if (age < 30) {
if (cc < 15) 150
else if (cc < 24) 210
else 330
} else if (age < 40) {
if (cc < 15) 180
else if (cc < 24) 330
else 420
} else if (age >= 50) {
if (cc < 15) 270
else if (cc < 24) 480
else 540
} else dur
}
ub_duration3 <- Vectorize(ub_duration_scalar)
ub_duration3(25,c(12, 18, 24))
## [1] 150 210 310