I'd like to apply an if_else function to several columns of my dataframe, with a dynamic name of variable to assign, the function is as follows:
retraitement <- function(Col, Taille) if_else(TAILLE== Taille,get(paste0("score_", str_replace(Col, "Score", ""), "_", Taille)),Col)
I've created the columns before and filled them with NA values :
columnsToAdd <- c(
"Score1", "Score13", "Score49")
df[,columnsToAdd]=NA
What I want is to apply this function to the columns specified above like :
df<- df%>%
mutate_at(all_of(columnsToAdd), retraitement, Taille = "PE") %>%
mutate_at(all_of(columnsToAdd), retraitement, Taille = "MGE")
The problem is that I have this error message :
Caused by error in
get()
: ! first argument has length > 1
How can I fix it ?
Example
If we take as an example "Score1" variable, the original df is:
Score1 | 1_PE | 1_MGE | TAILLE |
---|---|---|---|
NA | 12 | 28 | MGE |
NA | 14 | 32 | PE |
After applying the function, it will be in my mind:
Score1 | 1_PE | 1_MGE | TAILLE |
---|---|---|---|
28 | 12 | 28 | MGE |
14 | 14 | 32 | PE |
As displayed above, the values assignment would be :
If Taille == "GE" then Score1 = 1_GE
If Taille == "MGE" then Score1 = 1_MGE
So globally : If taille =="X" then Score1 = 1_X
It is important to keep in mind that I have several columns like "Score1" so applying a custom function would be better.
Thanks in advance