Use variable name for calculation in SAS

2019-06-04 10:24发布

问题:

I have a SAS dataset that looks like this:

var  _12  _41  _17
12      .   .   .
41      .   .   .
17      .   .   .

So for each var there is a column named _var.

I want to use an array or macro to populate all the missing values with the product of the row and column:

     _12  _41  _17
12  144   492  204
41  492  1681  697
17  204   697  289

Any thoughts on how to approach this? I want it to be completely general, so I don't need to know the names of the columns, and make no assumptions about their order or values, other than that they are all numbers.

回答1:

As all the variables (apart from var) begin with an underscore then it is easy to reference them in an array. You can then use the INPUT, COMPRESS and VNAME functions to extract the number and perform the calculation in a single line! Here is the code.

    data have;
    input var  _12  _41  _17;
    cards;
    12  .   .   .
    41  .   .   .
    17  .   .   .
    ;
    run;

    data want;
    set have;
    array nums{*} _: ;
    do i=1 to dim(nums);
        nums{i}=var*input(compress(vname(nums{i}),"_"),best12.);
    end;
    drop i;
    run;


标签: sas