Search code examples
sas

Using a function or calculation to refer to a SAS field name?


I need to populate a series of columns titled M0, M1, M2, etc. Below is the long-hand logic I've worked out, but now I'd like to streamline the code. See how I first count the months between two date fields to learn what column to populate.

if intck('month', start_dt, today_dt) = 0 then M0 = "Blue";
if intck('month', start_dt, today_dt) = 1 then M1 = "Blue";
if intck('month', start_dt, today_dt) = 2 then M2 = "Blue";

Conceptually I'd rather do something like this on a singular line of code instead:

"M"||intck('month', start_dt, today_dt) = "Blue";

So I want to "calculate" the proper column name, I guess.

Thanks for any help!


Solution

  • That is what an ARRAY is for.

    array month [0:3] m0-m3;
    month[intck('month', start_dt, today_dt)]= "Blue";
    

    In reality you will want to make sure the index is a valid value before using it.

    array month[0:3] m0-m3;
    index= intck('month', start_dt, today_dt) ;
    if index in (0:3) then month[index] = "Blue";
    else put 'Month out of range ' index= start_dt= ;