BookmarkSubscribeRSS Feed
CathyVI
Pyrite | Level 9

For each ID, I will like to find the count from the last day (e.g. Day3 for a1) up until the month where result is pos (positive). I have a sample data here,

data a;
input id result$  visitday $;
datalines;
a1 neg  day1
a1 neg  day2
a1 neg  day3
a1 neg month1
a1 pos month2
b2 neg day1
b2 neg day2
b2 pos month1
c3 neg day1
c3 neg day2
c3 neg month1
c3 neg month2
c3 pos month3
;
run;

3 REPLIES 3
PaigeMiller
Diamond | Level 26

Please show us the desired output.

 

What does "count from the last day up until the month where the result is positive" mean? How can you count with character variables?

--
Paige Miller
Kurt_Bremser
Super User

Your data step won't work, as the values for id are not numeric.

Simple code:

data want;
set have;
by id;
keep id count;
retain start;
if first.id then count = .;
if first.id or substr(visitday,1,3) = "day" then start = _n_;
if count = . and substr(visitday,1,5) = 'month' and result = "pos" then count = _n_ - start;
if last.id;
run;
Ksharp
Super User
data a;
input id $ result$  visitday $;
datalines;
a1 neg  day1
a1 neg  day2
a1 neg  day3
a1 neg month1
a1 pos month2
b2 neg day1
b2 neg day2
b2 pos month1
c3 neg day1
c3 neg day2
c3 neg month1
c3 neg month2
c3 pos month3
;
run;

data want;

do i=1 by 1 until(last.id);
 set a;
 by id;
 if visitday =: 'day' then start=i;
 if visitday =: 'month' and result='pos' and not found then do;found=1;end=i;end;
end;

count=end-start;
drop i start end found;
run;

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 649 views
  • 2 likes
  • 4 in conversation