BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
CHL0320
Obsidian | Level 7
Hi
 
I have a SAS question and would like to have your help.  I need to create a count variable when the day variable is in (1,6,7) per ID, and then assign that count variable to the max value. The order cannot be changed. For example
 
 
Data have: ID, day
 
A   7
A   4
A   5
B   4
B   1
B   7
B   3
C   7
C   1
C   2
D   2
D   3
D   7
E   1
E   2
E   3
E   4
 
Data  want is: ID, day, N_day
 
A   7   1
A   4   1
A   5   1
B   4   2 
B   1   2
B   7   2
B   3   2
C   7   3
C   1   3
C   6   3
D   2   1
D   3   1
D   7   1
E   2   0
E   2   0
E   3   0
E   4   0
 
Thank you for your help.
1 ACCEPTED SOLUTION

Accepted Solutions
PeterClemmensen
Tourmaline | Level 20

Your day variable is not the same in your two data sets.

 

Anyway, you can do like this

 

data have;
input id $ day;
datalines;
A   7
A   4
A   5
B   4
B   1
B   7
B   3
C   7
C   1
C   6
D   2
D   3
D   7
E   2
E   2
E   3
E   4
;

data want;
   N_day=0;
   do until (last.id);
      set have;
      by id;
      if day in (1, 6, 7) then N_day=N_day+1;
   end;
   do until (last.id);
      set have;
      by id;
      output;
   end;
run;

 

View solution in original post

2 REPLIES 2
34reqrwe
Quartz | Level 8

Why does the count increase by 1 at this line?

 

B   4   2 

PeterClemmensen
Tourmaline | Level 20

Your day variable is not the same in your two data sets.

 

Anyway, you can do like this

 

data have;
input id $ day;
datalines;
A   7
A   4
A   5
B   4
B   1
B   7
B   3
C   7
C   1
C   6
D   2
D   3
D   7
E   2
E   2
E   3
E   4
;

data want;
   N_day=0;
   do until (last.id);
      set have;
      by id;
      if day in (1, 6, 7) then N_day=N_day+1;
   end;
   do until (last.id);
      set have;
      by id;
      output;
   end;
run;

 

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

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
  • 2 replies
  • 1030 views
  • 0 likes
  • 3 in conversation