BookmarkSubscribeRSS Feed
RBRoma
Fluorite | Level 6

I am working with a dataset of time spent at the gym in SAS Studio.  This includes an ID, time-in, and time-out.  I have 119 columns for time-in and 119 for time-out.  I was able to input the data using the variable list in the screenshot attached.  Is there a similar way to perform gym_visit1 = out1 - in1 to get the amount of time spent at the gym per session without writing 119 different calculations?  Thank you. 

2 REPLIES 2
Astounding
PROC Star

The usual method for processing many variables in the same fashion is to use arrays:

 

data want;

set have;

array in {119} in1-in119;

array out {119} out1-out119;

array diff {119} gym_visit1-gym_visit119;

do _n_=1 to 119;

   if out{_n_} > . then diff{_n_} = out{_n_} - in{_n_};

end;

run;

 

Alternatively, you could have macro language generate 119 statements for you.  In its simplest form:

 

%macro differ;

   %local j;

   %do j=1 %to 119;

      gym_visit&j = out&j - in&j;

   end;

%mend differ;

 

data want;

set have;

%differ

run;

 

More complex macro coding would let you control how many statements to generate (instead of hard-coding 119), or the names of the incoming and outgoing variables.  In this case, simplest seems appropriate.

Patrick
Opal | Level 21

@RBRoma

Everything will become simple if you transpose your wide data structure to a long data structure. 

 

Using the code you've posted below amended code (not tested as no sample data available) should do the trick:

data newyear(keep=id t_in t_out) ;
  infile '/folders/myshortcuts/SAS/SAS HW #2/Data_Assignment2/NewYears.dat' dsd truncover ;
  input id (in1-in119 out1-out119) (:time8.) ;
  format in1-in119 out1-out119 time8.;
  array a_in {*} in:;
  array a_out {*} out:;
  do _i=1 to dim(a_in);
    t_in=a_in[_i];
    t_out_t=a_out[_i];
    if cmiss(t_in,t_out)>0 then output;
  end;
run;

data gymvisit;
  set newyear;
  duration_in_sec = t_in - t_out;
  format duration_in_sec time8.;
run;

 

Develop Code with SAS Studio

Get started using SAS Studio to write, run and debug your SAS programs.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 2 replies
  • 3489 views
  • 2 likes
  • 3 in conversation