Hello
I have a problem with my code.
I want to find the first and second non-missing value in a row so that the second one is not equal to the first one.
data want;
set have;
array value a-e;
array nvalue(5) _temporary_;
first= coalesce(of value(*));
do i = 1 to 5;
if value(i) ^= first then second = value (i);
end;
drop i;
run;
my result is like this:
A b c d e first second
8 8 8 4 8 8 4
5 8 . . . 5 .
. . . 4 8 4 8
Just those rows like the second row has problem. It shows ( . ) for the second one.
Thanks a lot
Try
if value{i} ne first and not missing(value{i}) then second = value {i};
Try
if value{i} ne first and not missing(value{i}) then second = value {i};
thanks alot
I'd recommend changing the DO loop:
do i = 1 to 5 until (second > . ) ;
Your loop (in its current state) continues even after populating SECOND. So it can replace a valid SECOND with a missing value.
I think you marked the wrong answer as correct. Use the answer with the WHILE () condition instead.
Update the test data to have a case with more than two distinct values to see the difference.
data have ;
input a b c d e expect1 expect2 ;
cards;
8 8 8 4 8 8 4
5 8 6 . . 5 8
. . . 4 8 4 8
1 1 1 1 1 1 .
. . . . . . .
;
You can also change your upper and lower bounds on the DO loop. No need to check the first item since it is either missing or equal to the previously calculated FIRST value. Use the DIM() function to make it easier to change the number of elements in the array.
data want;
set have;
array value a b c d e;
first= coalesce(of value(*));
do i = 2 to dim(value) while (missing(second));
if value(i) ^= first then second = value(i);
end;
drop i;
run;
Or you could calculate FIRST and SECOND in the same loop.
data want;
set have;
array value a b c d e;
do i = 1 to dim(value) while (missing(second));
if missing(first) then first=value(i);
else if value(i) ^= first then second = value(i);
end;
drop i;
run;
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.