DATA Step, Macro, Functions and more

Creating a conditional count variable

Accepted Solution Solved
Reply
Frequent Contributor
Posts: 138
Accepted Solution

Creating a conditional count variable

Hi,

I have a dataset at the person-day level (that is, each row is one day for one person). Each person in the dataset appears in multiple different rows. I need to be able to calculate scores for each person based on their values of other variables.

For example:

ID     Date     Var3     Var4

1     5/1/14    a          d

2     6/1/14    b          d

1     5/15/14  c          e

1     5/31/14  a          d

3     4/1/13    a          f

I would want to calculate one score by seeing how many values of "a" each person had for Var3 over time, and another by seeing how many values of "d" each person had for Var4 over time. '

Any help is much appreciated.


Accepted Solutions
Solution
‎06-03-2014 11:24 AM
Super Contributor
Posts: 275

Re: Creating a conditional count variable

This is what you want?

data want;

set have;

by id;

retain a_count d_count temp;

if first.id then do;

call missing(a_count,d_count,temp);

temp=var5;

end;

a_count+ifc(var3='a' and temp^=var5,1,0);

d_count+ifc(var4='d',1,0);

temp=var5;

if last.id then output;

drop temp;

run;

View solution in original post


All Replies
Super Contributor
Posts: 578

Re: Creating a conditional count variable

proc sql;

create table want as

select

     id,

     sum(var3='a') as a_count,

     sum(var4='d') as d_count

from

     have

group by id;

quit;

Super Contributor
Posts: 275

Re: Creating a conditional count variable

data step

proc sort data=have;

by id;

run;

data want;

set have;

by id;

retain a_count d_count;

if first.id then  call missing(a_count,d_count);

a_count+ifc(var3='a',1,0);

d_count+ifc(var4='d',1,0);

if last.id then output;

run;

Frequent Contributor
Posts: 138

Re: Creating a conditional count variable

If I use ifc, can I add additional conditions (for example, can I count values of "a" for var3 only if the value of var5 is different from the previous row)?

Solution
‎06-03-2014 11:24 AM
Super Contributor
Posts: 275

Re: Creating a conditional count variable

This is what you want?

data want;

set have;

by id;

retain a_count d_count temp;

if first.id then do;

call missing(a_count,d_count,temp);

temp=var5;

end;

a_count+ifc(var3='a' and temp^=var5,1,0);

d_count+ifc(var4='d',1,0);

temp=var5;

if last.id then output;

drop temp;

run;

Respected Advisor
Posts: 3,124

Re: Creating a conditional count variable

Proc Freq is built for counting ( you get the output into tables via ODS):

proc freq data=have;

table id*(var3 var4) /nocol nocum norow nopercent;

run;

Regards,

Haikuo

☑ This topic is SOLVED.

Need further help from the community? Please ask a new question.

Discussion stats
  • 5 replies
  • 905 views
  • 6 likes
  • 4 in conversation