Hi everyone,
I have code that selects the first non-missing variable from an array of variables:
DATA want;
set have;
array t(*) YA: ;
a=coalesce(of t(*));
RUN;
How do I adjust this code to instead select the first non-zero (and nonmissing) variable in the array?
Here is an example of my data:
ID Y1994 Y1996 Y1998 Y2000 Y2002 Y2004
01 . . . . 12 12
02 . . . . . .
03 . 14 . . . .
04 0 15 15 . . 15
05 . 0 17 16 . .
Here is what I would like:
ID Y1994 Y1996 Y1998 Y2000 Y2002 Y2004 a
01 . . . . 12 12 12
02 . . . . . . .
03 . 14 . . . . 14
04 0 15 15 . . 15 15
05 . 0 17 16 . . 17
Thanks,
AMIHIC
Use an ARRAY and a DO loop.
data have ;
input
ID $ Y1994 Y1996 Y1998 Y2000 Y2002 Y2004 ;
cards;
01 . . . . 12 12
02 . . . . . .
03 . 14 . . . .
04 0 15 15 . . 15
05 . 0 17 16 . .
;
data want ;
set have ;
array y y:;
do i=1 to dim(y) until (a not in (.,0)) ;
a=y(i);
end;
run;
proc print;
run;
Correct, coalesce takes the first non-missing, so would not work. You could do it a number of ways depending on what your data looks like - which you have not provided:
You could concatenate all the array into a string, then compress out missings.
You could loop over the array and find the Nth non missing, something like:
%let n=4; data want; set have; array t{*} yafs:; n=0; do i=1 to dim(t); if t{i} ne . then n=sum(n,1); if n=&n. then result=n; end; run;
Hi RW9,
I edited my original post to include a sample of my data.
AMIHIC
Use an ARRAY and a DO loop.
data have ;
input
ID $ Y1994 Y1996 Y1998 Y2000 Y2002 Y2004 ;
cards;
01 . . . . 12 12
02 . . . . . .
03 . 14 . . . .
04 0 15 15 . . 15
05 . 0 17 16 . .
;
data want ;
set have ;
array y y:;
do i=1 to dim(y) until (a not in (.,0)) ;
a=y(i);
end;
run;
proc print;
run;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.