Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

dplyr

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.

like image 706
pedram Avatar asked Mar 13 '23 16:03

pedram


1 Answers

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
like image 64
Sam Dickson Avatar answered Mar 16 '23 15:03

Sam Dickson