Search code examples
arrayssasdo-loops

SAS array DO loop calculation within data step


I have the following data set:

data have;
    input x10 x22 x13 x64;
cards;
20 10 30 1
;
run;

I want to create four new columns called log_x10, log_x22, log_x13, log_x64 which are the logs of the original columns. I know this is probably a fairly straightforward array, loop process, but I'm fairly new to arrays and can't quite get the syntax. Here is what I have:

data want;
    set have;
    array var[*] x: ;
    do j=1 to dim(var);
        logx[j]=log(var[j]);
    end;
run;

It won't always be four variables, sometimes less or more. I have the id numbers pulled into a macrolist id=(10,22,13,64) so can try to use something like that to name.

Ideas? Thanks.


Solution

  • I think you'll need to establish the length of your array at in order to declare your result array. Fortunately you can load it into a macro variable with with short datastep.

    data have;
        input x10 x22 x13 x64;
    cards;
    20 10 30 1
    ;
    run;
    
    data _null_;
        set have (obs=1);
        array vars[*] x: ;
        call symput('array_length',cats(dim(vars)));
    run;
    
    data want;
        length logx1-logx&array_length. 8;
        set have;
        array vars[*] x: ;
        array logvars[*] logx1-logx&array_length.;
        do j=1 to dim(vars);
            logvars[j]=log(vars[j]);
        end;
    run;