4

I have a data.frame DF that looks a little like this

category var1 var2 
apples    1    4
bananas   3    3
orange    4    1 
kiwis     2    3

I also have created a simple custom function that generates an output based on two parameters:

annualize_fte <- function(tenure, amount)
{
    if (tenure==0) return(0)

    if (tenure>12) {
        result = amount
    } else {
        t_factor = 12 / tenure
        result = amount * t_factor
    }
    return(result)
}

I'd like to create a third column var3 that is the result of applying annualize_fte(var1, var2) to each row.

I've tried the following and have failed:

mutate(DF, var3=annualize_fte(var1, var2)) 
apply(DF, 1, annualize_fte, DF$var1, DF$var2)

I get errors around unused arguments or errors that condition has length >1.

1
  • 1
    ifelse(x==0, 0, ifelse(x>12, x, y*12/x))
    – Khashaa
    Jan 8, 2016 at 17:04

1 Answer 1

7

Perhaps you'd like to try Vectorize() to make it so your function can use and return vectors:

annualize_fte_v <- Vectorize(annualize_fte)

(DF$var3 <- annualize_fte_v(DF$var1,DF$var2))
#   category var1 var2 var3
# 1   apples    1    4   48
# 2  bananas    3    3   12
# 3   orange    4    1    3
# 4    kiwis    2    3   18
2
  • That's exactly what I needed! That's a pretty neat function, thank you.
    – pedram
    Jan 8, 2016 at 17:15
  • Just to elaborate another way: Multivariate function application is usually handled by Map or mapply. Here we'd use mapply(annualize_fte, tenure = DF$var1, amount = DF$var2) to get the values. Vectorize here creates a modified version of annualize_fte built on top of mapply.
    – TJ Mahr
    Jan 8, 2016 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.