Search code examples
sasstring-concatenationsas-macro

SAS Concatenation based on values


Below is the sample data.

NAME VAR2 VAR3 VAR4 VAR5
ABC    X   Y          2
DEF    P   Q    R     3
GHI    L              1

The count of variables (from VAR2-VAR4) is present under VAR5 for each record, I want the following output with NewVar as the concatenation of the variables which contain a value.

NAME VAR2 VAR3 VAR4 VAR5  NewVar
ABC    X   Y          2     X,Y
DEF    P   Q    R     3     P,Q,R
GHI    L              1     L

I have no clue how to do it in SAS. Any help is appreciated.


Solution

  • Use the CATX() function to concatenate the variables; with this function you have the option to specify the delimiter character to use between the values. Ex. CATX(',',VAR2,VAR3,VAR4)

    Input Data:

    data have;
    input NAME $ VAR2 $ VAR3 $ VAR4 $ VAR5;
    datalines;
    ABC    X   Y    .      2
    DEF    P   Q    R     3
    GHI    L   .    .       1
    ;
    run;
    

    Solution:

    data want;
    set have;
    NewVar= catx(',',VAR2,VAR3,VAR4);
    run;
    

    or

    %let list=VAR2,VAR3,VAR4;
    data want2;
    set have;
    NewVar= catx(',',&list.);
    run;
    

    or (Tom's Recommendation)

    data want3;
    set have;
    NewVar= catx(',',of var2-var4);
    run;
    

    Output:

    NAME=ABC VAR2=X VAR3=Y VAR4=  VAR5=2 NewVar=X,Y 
    NAME=DEF VAR2=P VAR3=Q VAR4=R VAR5=3 NewVar=P,Q,R 
    NAME=GHI VAR2=L VAR3=  VAR4=  VAR5=1 NewVar=L