This is my data:
# Test datasets
test_df <- data.frame(A =c(1, 2, 3, 3, 4), AKH_UL =c(111, 222, 333, 444, 555), AKH_LL = c(222, 333, 444, 555, 666),
AKH_UU = c(213, 242, 253, 546, 243), AKH_LU = c(453, 855, 784, 352, 585), FFL_UL =c(111, 222, 333, 444, 555), FFL_LL = c(222, 333, 444, 555, 666), FFL_UU = c(213, 242, 253, 546, 243), FFL_LU = c(453, 855, 784, 352, 585))
I want to create two columns, AKH
and FFL
. The value of the column depends on conditions and each condition is connected to a certain function:
Simplified functions:
# Case 1:
myfunction1 <- function(cost, cost_LL, cost_UL, cost_LU, cost_UU){
test_df$cost <- cost_LL *cost_UL + cost_UU * cost_LU
}
# Case 2:
myfunction2 <-function(cost,cost_LL, cost_LU){
test_df$cost <- cost_LL *cost_LU
}
# Case 3:
myfunction3 <-function(cost,cost_UL, cost_UU){
test_df$cost <- costUL *costUU
}
Right now I'm doing it in two separate steps for each column. For example like this for AKH:
test_df$AKH <-
ifelse(test_df$A == 1,
myfunction1(test_df$AKH, test_df$AKH_LL, test_df$AKH_UL, test_df$AKH_LU, test_df$AKH_UU),
ifelse((test_df$A == 2,
myfunction2(test_df$AKH, test_df$AKH_LL, test_df$AKH_LU),
ifelse((test_df$A == 3,
myfunction3(test_df$AKH, test_df$AKH_UL, test_df$AKH_UU),
99999))))
The same calculation I do for a second term, just with FFL instead of AKH inside the formulas.
This looks pretty horrible (in rl it's not only two but 10 columns) and I'm afraid the other children will make fun of me when they see my script.
I checked out this question, but wasn't able to fully transfer it to my problem, because I have no idea how to make the connection between the variable name in the formula and the column name.