sas

How to loop to get column name?


The general idea is to get the column name, and calculate the mean and std one by one in SAS. But there are over 50 columns, and no pattern in their column names. I don't know how to get using SAS, but the idea I want is as below by using R:

Let's use a simple data example.

mydata<-data.frame(id=c(1:10),
class=c(1,1,1,1,1,2,2,2,2,2),
age=sample(30:100, 50, replace = TRUE),
bmi=sample(20:30, 50, replace = TRUE),
bmi_week4=sample(20:30, 50, replace = TRUE),
bmi_week8=sample(20:30, 50, replace = TRUE),
hba1c=sample(5:10, 50, replace = TRUE),
hba1c_week4=sample(5:10, 50, replace = TRUE),
hba1c_week8=sample(5:10, 50, replace = TRUE)
)

names<-colnames(mydata[,-c(1,2)])

for (i in 1:length(names)){
this_col=names[i]

#starting from here is the SAS code
  proc univariate
  data = mydata noprint;
  by class;
  var this_col;
  output out = this_col_out
  n = _n mean = _mean std = _std;
  run;

  # I get the format of mean±std for each variable, and save in output_&i.
  data output_&i.;
  set this_col_out;
  this_col=strip(put(_mean,7.2)) ||'±'|| strip(put(_std,8.2));
  run;
  
  #through transpose, I can get the format such as age: 64.5 ± 20.7
  proc transpose data=output_&i. out=w_output_&i.(drop=_label_);
  var this_col;
  run;
}

data all;
set w_output_:;
run;

So how to get the idea from R and integrate it into SAS? Thanks.


Solution

  • You can use stackodsout to get a summary listing

    ods output summary=want (drop=_control_);
    proc means print data=have stackodsoutput sum mean std nway ;
      class class ;
    run ;
    

    will produce this output data set enter image description here