I have the following macro in SAS, and I'm trying to migrate it to R:
%macro recode_var(var=);
if &var in (1,2,3,4,5) then do;
if &var = 1 then &var._r = 0;
if &var = 2 then &var._r = 25;
if &var = 3 then &var._r = 50;
if &var = 4 then &var._r = 75;
if &var = 5 then &var._r = 100;
end;
%mend;
This is called by the line
%recode_var(var=Q7_1);
This creates a new variable Q7_1_r with values based on the values of Q7_1. I have 100 variables to call the macro for (e.g. Q7_5, Q15_6, Q35_4). What is the best way to write an R equivalent?
I wrote the following code (newfile is the name of the data frame)
sevenvar <- function(var){
newfile <- mutate(newfile, Q7_1_r = case_when(var == 1 ~ 0,
var == 2 ~ 25,
var == 3 ~ 50,
var == 4 ~ 75,
var == 5 ~ 100))
}
sevens <- sevenvar(newfile$Q7_1)
head(sevens)
It worked for a specific variable (Q7_1), but if I were to do it all this way, I'd have to rewrite the above block of code 100 times, for each of the variables I want to apply it do. I'm thinking surely there has to be a more efficient way - something that could take in a variable (var) and create a new variable var_r, with the function then called upon for each variable it applies to by means of a one liner:
sevens <- sevenvar(var)
changing the value of var every time I run the above. e.g. sevens <- sevenvar(newfile$Q7_5), sevens <- sevenvar(newfile$Q15_6), sevens <- sevenvar(newfile$Q35_4). I just need to get the block of code right to begin with so I can replicate the results of the SAS macro in R.
Any advice welcome. Thank you.