1

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.

2 Answers2

0

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]]
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Actually this isn't a very efficient SAS solution either :) – Reeza Jul 27 '18 at 15:49
  • @Reeza Ha. That's good to know. My SAS is a bit rusty. Would you use some sort of collection type as well in SAS? – MrFlick Jul 27 '18 at 15:57
  • I would probably recommend stacking all and filtering at once. `data want; set examples1-examples4; where sex=1; run;` That would stack all the data and filter at once. There's a few ways to shortcut that reference list for the SET statement. – Reeza Jul 27 '18 at 16:01
-1

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.user.05apr
  • 5,356
  • 3
  • 22
  • 39
  • This wouldn't align with a macro solution because you pretty much need to know the number of data sets ahead of time, note the hardcoded 4 in several places. SAS doesn't require that knowledge ahead of time. – Reeza Jul 27 '18 at 21:32