Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SAS return first value in the group for the rest of the group

Suppose I have the following data but I basically want to copy the first value of a and b for the rest of the values in the group (the table on the bottom).

For example, in group 1, the first value in a = 3. I want to replace 2, 4, 1 in the group with 3 -- same for variable b.

Original Data:

grp a   b
----------
1   3   2
1   2   1
1   4   2
1   1   3
2   2   4
2   1   1
2   2   2
2   3   1

Updated Data:

grp a   b
----------
1   3   2
1   3   2
1   3   2
1   3   2
2   2   4
2   2   4
2   2   4
2   2   4

Thanks in advance.

like image 529
Ken Avatar asked Oct 12 '25 08:10

Ken


1 Answers

You can use by-group processing and the retain statement to do this. Note that the input dataset will need to be sorted by group first for this to work.

data output(keep=grp a b);
  retain firsta firstb;
  set input;
  by grp;
  if first.grp then do;
    firsta = a;
    firstb = b;
  end;
  else do;
    a = firsta;
    b = firstb;
  end;
run;
like image 190
Gary Avatar answered Oct 14 '25 01:10

Gary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!