pedram
pedram

Reputation: 3087

Apply custom function to two columns for every row in data frame in R

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.

Upvotes: 4

Views: 3540

Answers (1)

Sam Dickson
Sam Dickson

Reputation: 5239

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

Upvotes: 7

Related Questions