Compress a range of Variables.

Reply
Contributor
Posts: 66

Compress a range of Variables.


Hi Community,

I have an issue with compressing a range of variables. Here is what I wanted to do

Data have;

V1          V2          V3     ...     Vn

ab           cd          ef

af            bd   

ab           cd        ed                mn

I want to compress these 'n' variables by a single variable where each element of the old variables are separated by a comma.

The new variable should look like 

V1          V2          V3     ...     Vn               NewVar

ab           cd          ef                                   ab,cd,ef..

af            bd                                                 af,bd,

ab           cd        ed                mn

My attempt

Data Want;

Arrary  V(I)  $     V1-V&N;   N is dynamic variable.

Set  have;

do i= 1 to &N;

NewVar=Compress(V1||','||-||Vn);       /* (Thinking if SAS understands the range the way it works for drop statement as drop V1-V&N)*/

End;

RUN;

Thanks!

PROC Star
Posts: 7,363

Re: Compress a range of Variables.

Here are a couple of ways depending upon whether you do or don't want additional commas to represent missing variables:

data have;

  input (V1-V4) ($);

  length newvar2 $50;

  array vars(*) $ v1-v4;

  newvar1=catx(',',of vars(*));

  newvar2=trim(left(vars(1)));

  do _n_=2 to dim(vars);

    newvar2=trim(left(newvar2))||","||trim(left(vars(_n_)));

  end;

  cards;

ab cd ef .

de . ab .

af bd . .

ab cd ed mn

;

Contributor
Posts: 66

Re: Compress a range of Variables.

Art, Thanks a lot!

Super User
Posts: 17,829

Re: Compress a range of Variables.

CatX function instead of compress Smiley Happy

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