I am working with a large data frame and I need/want to use more efficient code.
This is my starting point:
library(data.table)
dt<-data.table(Customer = c("John","Sally","Michael","David"),
Premium=c(1000,950,1125,1500),
Factor_1=1.2,
Factor_2 =c(.98,.95,.9,.75),Factor_3=c(1,1.2,1.4,1.5))
This is the desired result (I want to create Premium_1, Premium_2, Premium_3):
Inefficient_code_answer<-dt%>%
mutate(Premium_1 = Premium*Factor_1)%>%
mutate(Premium_2 = Premium*Factor_1*Factor_2)%>%
mutate(Premium_3 = Premium*Factor_1*Factor_2*Factor_3)
I tried to use purrr
dt%>%
mutate(Premium_3 = Premium * pmap_dbl(list(Factor_1:Factor_3),prod))
But list() does not play well with " : " sequences (Unless I just do not know how).
I have about 25 to 30 factors I need to apply to a base premium, and I need the premium values at each step. I currently have it all typed out in a script, but that is a nightmare to adjust when I want to add or take away a step (or factor).
Thanks