John SHEN
John SHEN

Reputation: 3

Replace SAS macro loops in R

Say I have the following dataframe and I want to create individual subset dataframes as me1, me2, me3.....

In R I would manually do the following:

data1 <- data.frame(a = runif(4),
                    b = runif(4),
                    c = runif(4),
                    d = c("a","a","b","c"))


me1 <- subset(data1,data1$d == "a")
me2 <- subset(data1,data1$d == "b")
me3 <- subset(data1,data1$d == "c")

In SAS, I would write a macro loop which is like the following to automatically generate those meX datasets:

%let vars = a b c;
%do count1= 1 %to 3;
  % let thisVar = %scan(&var.,&count1.);
  data me&count1.;
    set data1;
    where d = "&thisvar";
  run;
%end;

Are there similar ways in R to do this?

Thanks!

Regards, John

Upvotes: 0

Views: 201

Answers (2)

variable
variable

Reputation: 1023

Probably a silly way to do it, since I'm using lapply and dplyr. Also I'm not naming the items.

library(dplyr)
data1 <- data.frame(a = runif(4),
                    b = runif(4),
                    c = runif(4),
                    d = c("a","a","b","c"))

custom.filter <- function(i){
  return(filter(data1,d==i))
}

melist <- lapply(unique(data1$d),custom.filter)

Upvotes: 0

akrun
akrun

Reputation: 887223

We can try list2env if individual objects are needed in the global environment. (I would prefer to place this in a list with split). The list elements after the split are named as the unique elements of 'd' column that was used for splitting. Change the names to the preferred one by setNames and paste0 (as there is a pattern for 'me1', 'me2', etc), and use list2env so that the individual me1, me2 etc are created

list2env(setNames(split(data1, data1$d), 
          paste0('me', 1:3)), envir=.GlobalEnv)

me1
#          a          b         c d
#1 0.1455141 0.02331238 0.5732288 a
#2 0.5377224 0.37848993 0.6632085 a

Upvotes: 1

Related Questions