Solved
Contributor
Posts: 22

# first and second non-missing value in a row

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

Accepted Solutions
Solution
‎06-16-2017 10:11 PM
Super User
Posts: 10,555

## Re: first and second non-missing value in a row

Try

``if value{i} ne first and not missing(value{i}) then second = value {i};``
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code

All Replies
Solution
‎06-16-2017 10:11 PM
Super User
Posts: 10,555

## Re: first and second non-missing value in a row

Try

``if value{i} ne first and not missing(value{i}) then second = value {i};``
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
How to convert datasets to data steps
How to post code
Contributor
Posts: 22

thanks alot

Super User
Posts: 6,927

## Re: first and second non-missing value in a row

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.

Contributor
Posts: 22

Thanks a lot
Super User
Posts: 8,272

## Re: first and second non-missing value in a row

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;``````
☑ This topic is solved.