Home > OS >  SAS EG How to compare cell values in an array loop?
SAS EG How to compare cell values in an array loop?

Time:06-28

I am currently trying to compare cell values on the same row over multiple columns, but having issues with referencing the correct cells.

My data currently is this:

col1 col2 col3 col4 col5 col6
a b c d e f
a b c d e e
a b c d d d

I would like to compare col{i} to col{i 1} and drop values when repeated to give:

col1 col2 col3 col4 col5 col6
a b c d e f
a b c d e -
a b c d - -

My current code is:

data want;
set have;
array c{*} col;
do i = 1 to dim(c);
do j = i 1;
if c{i} = c{j} then .;
else c{i};
end;
end;
run;

TIA

CodePudding user response:

data want;
  set have;
  array c{*} col;
  do i =  dim(c) to 2 by -1;   *no reason to check #1;
    if c{i} = c{i-1} then call missing(c{i});   *if identical to prior, clear out;
  end;
run;

You don't need two loops - just one - as you're just checking the record "before" (or "after", but "before" is easier to mentally comprehend, at least for me). Start on 2, check the one prior, and if identical, clear it out.

Importantly, this goes in reverse order (so it gets the d situation above) - if you go left to right, it won't get the last d as it won't compare to the right one.

  • Related