MetallicPriest
MetallicPriest

Reputation: 30745

How can I add more than 1 row for a row in Data Step of SAS

Let us say, I have a table like this.

# ID, X, Y
1, 0, 1
2, 1, 0
3, 1, 1

My resulting output should look like this

# ID, X, Y, R
1, 0, 1, Y
2, 1, 0, X
3, 1, 1, X
3, 1, 1, Y

So, you can see that for ID 3, we now have two rows instead of one, as both X and Y are one there, and the R column should have an entry for all columns with value 1.

So, my question is, how can this kind of flattening be done with the Data Step of SAS? Note here that in my case, both X and Y cannot be zero. At least one of them would be 1.

Upvotes: 0

Views: 420

Answers (1)

Richard
Richard

Reputation: 27498

Use an OUTPUT statement as part of a IF THEN do block clause.

  if x = 1 then do;
    r = 'x';
    output;
  end;
  if y = 1 then do;
    r = 'y';
    output;
  end;

If you have many variables that need to be Arrrrrified use a variable ARRAY

  array myRvars x y z p q r s t u z1-z10;
  do index = 1 to dim(myRvars);
    if myRvars(index) = 1 then do;
      r = vname(myRvars(index));
      output;
    end;
  end;

Upvotes: 1

Related Questions