Search code examples
variablescountsas

How do I uncondense a table in SAS


I’m trying to figure out how to take one table and break it out to two separate tables. In the below example I would want Jim and Steve to be in one table and Joy and Nancy to be in another one. I thought assigning numbers with a new variable would help me be able to break the tables out into (1) and (2) but how would I create a new variable count that works that way?

ID , Name 

T999999, Jim 
T999999, Joy
V888888, Steve
V888888, Nancy

My thoughts:

ID , Name, (new variable)

T999999, Jim, 1
T999999, Joy, 2
V888888, Steve, 1
V888888, Nancy, 2

Then I could just make a table of 1s and then a table of 2s.


Solution

  • You seem to be assuming that each ID value has two observations. In that case you could easily split the dataset into two by writing the first observation for a BY group into one dataset and the rest into the other.

    data want1 want2;
      set have;
      by id;
      if first.id then output want1;
      else output want2;
    run;
    

    Note that if some of the BY groups (ID values in this case) don't have exactly two observations then WANT1 and WANT2 might not have the same number of observations.

    You can also use BY group processing to add your new variable, let's call it ROW.

    data want;
      set have;
      by id;
      if first.id then row=1;
      else row+1;
    run;
    

    Note that with that new ROW variable on the dataset you do not really need to split the data. Instead you can just use a WHERE statement (or WHERE= dataset option) to select the observations you want.

    proc print data=want;
      where row=1;
    run;