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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With