Hi,
I have a dataset "Reproduction" with data from artificial inseminations(AI) in animals during 1 oestrous period.
Data Reproduction
ID AI1 AI2 AI3 AI4 AIn
1 B2 B2 B1 B2 4
2 B1 B1 B1 . 3
3 B1 B3 B3 B3 4
4 B2 B2 B2 . 3
5 B1 B1 . . 2
...(5400 obs)
The values "B1, B2 or B3" are male ID. I want to know if inseminations are with same male (event '1') or different male (event '0'), like this:
Data Reproduction
ID AI1 AI2 AI3 AI4 AIn Want
1 B2 B2 B1 B2 4 0
2 B1 B1 B1 . 3 1
3 B1 B3 B3 B3 4 0
4 B2 B2 B2 . 3 1
5 B1 B1 . . 2 1
...(5400 obs)
Just test if there is ever a value that does not match the first one.
data want;
set have ;
array ai ai1-ai4 ;
do index=1 to ain until(want=0);
want = ai[1] = ai[index] ;
end;
drop index;
run;
Just test if there is ever a value that does not match the first one.
data want;
set have ;
array ai ai1-ai4 ;
do index=1 to ain until(want=0);
want = ai[1] = ai[index] ;
end;
drop index;
run;
Tom,
What if the first variable is missing ?
data have; input ID AI1 $ AI2 $ AI3 $ AI4 $ AIn; cards; 1 B2 B2 B1 B2 4 2 B1 B1 B1 . 3 3 B1 B3 B3 B3 4 4 B2 B2 B2 . 3 5 . B1 . . 2 ;
I doubt that is what they actually have, why have the counter variable if missing values are not at the end?
But it is not hard to adjust for missing values.
data want;
set have ;
array ai ai1-ai4 ;
want=1;
do index=1 to ain while(missing(ai[index]));
end;
do index2=index+1 to dim(ai) until(want=0);
if not missing(ai[index2]) then want = ai[index] = ai[index2] ;
end;
drop index index2;
run;
Tom,
What if all the variable were missing ?
data have; input ID AI1 $ AI2 $ AI3 $ AI4 $ AIn; cards; 1 B2 B2 B1 B2 4 2 B1 B1 B1 . 3 3 B1 B3 B3 B3 4 4 B2 B2 B2 . 3 5 . . . . 2 ;
What is the right answer for a subject with all missing values?
That case is not hard to test for.
array ai ai1-ai4 ;
if cmiss(of ai[*]) = dim(ai) then ....
Tom,
I think should be zero.
data have;
input ID AI1 $ AI2 $ AI3 $ AI4 $ AIn;
cards;
1 B2 B2 B1 B2 4
2 B1 B1 B1 . 3
3 B1 B3 B3 B3 4
4 B2 B2 B2 . 3
5 B1 B1 . . 2
;
data want;
if _n_=1 then do;
length k $ 80;
declare hash h();
h.definekey('k');
h.definedone();
end;
set have;
array x{*} $ AI1-AI4;
do i=1 to dim(x);
if not missing(x{i}) then do; k=x{i};h.ref();end;
end;
want=(h.num_items=1);
h.clear();
drop i k;
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.