simple [SAS] macro in [R], how?

2019-07-28 17:53发布

问题:

I have datasets called example1,example2,example3,example4 of which variable is SEX(1 or 2) in working library and I've made datasets called exampleS1,exampleS2,exampleS3,exampleS4 restricted to SEX=1 by using MACRO in SAS

like this way.

%macro ms(var=);
data exampleS&var.;

set example&var.; IF SEX=1;
run; 
%mend ms;%ms(var=1);%ms(var=2);%ms(var=3);%ms(var=4);

Now, I want to do this job in R It's bit not easy to do this in R to me. How can I do it? (assuming example1,example2, example3,example4 are data.frames)

Thank you in advance.

回答1:

Having variables with numeric index in the name is a very SAS thing to do, and not at all very R like. If you have related data.frames, in R, you keep them in a list. There are many ways to read in many files into a list (see here). So say you have a list of data.frames

examples <- list(
    data.frame(id=1:3, SEX=c(1,2,1)),
    data.frame(id=4:6, SEX=c(1,1,2)),
    data.frame(id=7:9, SEX=c(2,2,1))
)

Then you can get all the SEX=1 values with

exampleS <- lapply(examples, subset, SEX==1)

and you access them with

exampleS[[1]]
exampleS[[2]]
exampleS[[3]]


回答2:

You should program R the R-way, not the SAS-way, because this will lead to endless pain. SAS-macro-language and R don't mix imo, but this is how:

 # create example df's
 for (i in 1:4) {
   assign(paste0("example", i), data.frame(sex = sample(0:1, 10, replace = T)))
 }
 example1; example2; example3; example4

 # filter and store result in a list of df's
 l <- list(example1 = example1, example2 = example2, example3 = example3, example4 = example4)
 want <- lapply(l, function(x) subset(x, sex == 1))
 want$example1; want$example2; want$example3; want$example4 # get list of data frames
 # almost certainly what you should do

 # in principle possible to this too, but advise against it
 list2env(lapply(l, function(x) subset(x, sex == 1)), .GlobalEnv)
 example1; example2; example3; example4


标签: r macros sas