BookmarkSubscribeRSS Feed
marleeakerson
Calcite | Level 5

Hello, 

 

I am trying to run a frequency but need some help. 

 

Using this sample data set: 

ID       Result

1         Pos

1         Neg

2         Pos

2         Neg

2         Pos

3         Pos

4         Neg

4         Pos

 

I am trying to run a frequency to see the frequency of people (IDs) who went from positive to negative, how many went from negative to positive, and all the other combinations (pos to neg and then back to pos, etc.). 

 

Can someone help me out with this? 

 

Thank you!

2 REPLIES 2
Kurt_Bremser
Super User

Prepare counts for changes:

data prefreq;
set have;
by id;
_result = lag(result);
if first.id
then do;
  count_neg_to_pos = 0;
  count_pos_to_neg = 0;
end;
else do;
  if _result = "Neg" and result = "Pos" then count_neg_to_pos + 1;
  if _result = "Pos" and result = "Neg" then count_pos_to_neg + 1;
end;
if last.id;
drop result_result;
run;
FreelanceReinh
Jade | Level 19

Hello @marleeakerson,

 


@marleeakerson wrote:

I am trying to run a frequency to see the frequency of people (IDs) who went from positive to negative, how many went from negative to positive, and all the other combinations (pos to neg and then back to pos, etc.).


Do you want to count an ID with, e.g., Pos followed by Neg in the same category as an ID with four times Pos followed by three times Neg (because both went from Pos to Neg), but not in the same category as an ID that after this change switched back to Pos?

 

If so, try this:

data want;
length seq $100;
do until(last.id);
  set have;
  by id result notsorted;
  if first.result then seq=catx(',', seq, result);
end;
drop result;
run;

proc freq data=want;
tables seq;
run;

This assumes that your dataset (HAVE) is sorted by ID. (Add a PROC SORT step if this is not the case.) Adapt the length of character variable SEQ (100) as needed to accommodate the relevant sequences "Pos,Neg,Pos,..." etc.

 

 

SAS Innovate 2025: Register Now

Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!

Mastering the WHERE Clause in PROC SQL

SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.

Find more tutorials on the SAS Users YouTube channel.

Discussion stats
  • 2 replies
  • 420 views
  • 0 likes
  • 3 in conversation