I have a series of variables with values 1.2, 2.5 etc. I would like to separate the numbers by decimal, so that I create a new column for the whole number and the decimal point, and then assign a total score.
HT_Q1 <- c(1.2, 2.5, 7.4)
HT_Q2 <- c(2.5, 8.5, 9.5)
AT_Q1 <- c(2.4, 1.2, 1.4)
AT_Q2 <- c(6.5, 1.5, 9.10)
df <- data.frame(HT_Q1, HT_Q2, AT_Q1, AT_Q2)
I can do this using mutate:
mutate(df,
HT_Q1_G = trunc(HT_Q1),
HT_Q1_B = HT_Q1 %% 1 * 10,
HT_Q1_P = (HT_Q1_G * 6) + HT_Q1_B)
However, I would like to write a function so I don't have to repeat the above code for each variable. Is it possible to pass each variable (HT_Q1, HT_Q2 etc.) as an argument to the function and create the corresponding variables (e.g. HT_Q2_G, HT_Q2_B, AT_Q2_G etc.)?
I have tried to create variable names based on the argument I pass to the function but it does not work:
edit_score <- function(var){
mutate(df,
paste0(var, "_G") = trunc(var),
paste0(var, "_B") = var %% 1 * 10,
paste0(var, "_P") = (paste0(var, "_G") * 6) + paste0(var, "_B"))
}
edit_score(HT_Q1)
edit_score(HT_Q2)
edit_score(AT_Q1)
edit_score(AT_Q2)
I am new to R and come from a SAS background where I am used to using the macro compiler to adjust text in code before it is executed.