Help using Base SAS procedures

choose latest 6 months of dates as variables

Reply
Super Contributor
Posts: 401

choose latest 6 months of dates as variables

Hi,  I have a dataset with Dates as variables (Eg. Jan2008, Feb2008, Mar2008..... Oct2013, Nov2013)... how in SAS can I pick only the latest 6 months? so in this case only Jun2013 to Nov2013 .. I'm asking this becasue I want to automate it, and not change the months every month.

Thanks

Super User
Posts: 19,806

Re: choose latest 6 months of dates as variables

Here's a simple way, not the most efficient but easy to follow and easy to modify:

I create 1 macro variables that contain the names of the months of interest that can then be used in a keep statement in another data step. You can tweak the start date and the count intervals as needed.

%let start_date=&sysdate;

%put &start_date;

data temp;

    do i=1 to 6;

        date=intnx('month', "&start_date"d, -1*i);

        date_formatted=put(date, monyy7.);

        output;

    end;

run;

proc sql;

     select date_formatted  into :keep_date_var separated by " "

from temp;

quit;

%put &keep_date_var;

data want;

set have;

keep id &keep_date_var;

run;

Super Contributor
Posts: 253

Re: choose latest 6 months of dates as variables

I first off would suggest not having a dataset with months as variables.  Store it in normalized form with months as rows.  Then you can easily select the last 6 months' worth of data using a WHERE or subsetting IF statement, and if needed transpose back.

If you must keep it in horizontal format, you could select the variable names from dictionary.columns (or proc contents output) into a macro variable.  Substitute proper names for LIBNAME and MEMNAME below (MEMNAME = dataset name).

proc sql;

select name into :collist separated by ' '

from dictionary.columns

where libname='WORK' and memname='HAVE'

and input(name,MONYY.) ge intnx('Month','01NOV2013'd,-5); *you can easily adjust this to be programmatic, not sure what your conditions are for determining 'last month' - use INTNX to pick last 6 months once you have that defined [macro variable, last actual calendar month, etc.];

quit;

data want;

set have;

keep &colllist.; *and any other needed variables.;

run;

Super Contributor
Posts: 401

Re: choose latest 6 months of dates as variables

Great help.. thanks to alll

Ask a Question
Discussion stats
  • 3 replies
  • 1009 views
  • 7 likes
  • 3 in conversation