I have a dataframe, which has 2 columns: date and return. Now I want to mutate multiple new columns, that are depending on two parameters: the threshold-parameter and the lag-parameter. The functionality is simple. The new column is calculated as follows:
var= ifelse(lag(return, n= lag_day)>threshold,return, NA))
If the lag(return) is higer than the threshold, than give me the return-value, else give me NA.
Here are the values for the thresholds and the lag_days:
threshold=c(2,4,6)
lag_day=c(1,2,3)
Here I'm solving my problem manually:
test<-df%>%
mutate(var_t1_lag1= ifelse(lag(return, n= lag_day[1] )>threshold[1],return, NA))%>%
mutate(var_t2_lag1= ifelse(lag(return, n= lag_day[1] )>threshold[2],return, NA))%>%
mutate(var_t3_lag1= ifelse(lag(return, n= lag_day[1] )>threshold[3],return, NA))%>%
mutate(var_t1_lag2= ifelse(lag(return, n= lag_day[2] )>threshold[1],return, NA))%>%
mutate(var_t2_lag2= ifelse(lag(return, n= lag_day[2] )>threshold[2],return, NA))%>%
mutate(var_t3_lag2= ifelse(lag(return, n= lag_day[2] )>threshold[3],return, NA))%>%
mutate(var_t1_lag3= ifelse(lag(return, n= lag_day[3] )>threshold[1],return, NA))%>%
mutate(var_t2_lag3= ifelse(lag(return, n= lag_day[3] )>threshold[2],return, NA))%>%
mutate(var_t3_lag3= ifelse(lag(return, n= lag_day[3] )>threshold[3],return, NA))
But is there a solution that would it make easier? Maybe with one or two apply-functions?
Here is my example-dataframe:
df <- tibble(
date= today()+0:12,
return=c(1,2.5,2,3,5,6.5,1,9,3,2,4,7,2)
)