Hello, I'm looking for a way to create a variable that will give me the total count for another variable for each participant ID. For example, If I have 'var1' in the original dataset:
ID | var1 |
1 | 0 |
1 | . |
1 | 1 |
1 | 0 |
1 | 1 |
1 | . |
1 | 1 |
1 | 0 |
1 | 1 |
1 | 0 |
2 | 0 |
2 | 1 |
2 | . |
2 | 0 |
2 | 0 |
2 | 1 |
2 | 1 |
I'd end up with a new variable 'totalcount':
ID | var | totalcount |
1 | 0 | 4 |
1 | . | 4 |
1 | 1 | 4 |
1 | 0 | 4 |
1 | 1 | 4 |
1 | . | 4 |
1 | 1 | 4 |
1 | 0 | 4 |
1 | 1 | 4 |
1 | 0 | 4 |
2 | 0 | 3 |
2 | 1 | 3 |
2 | . | 3 |
2 | 0 | 3 |
2 | 0 | 3 |
2 | 1 | 3 |
2 | 1 | 3 |
Thank you.
proc summary nway data=have;
class id;
var var1 var2 var3; /* Or use var var1-var3; if the names have consecutive suffix numbers */
output out=sums sum=/autoname;
run;
data want;
merge have sums;
by id;
run;
proc summary nway data=have;
class id;
var var1;
output out=sums sum=totalcount;
run;
data want;
merge have sums;
by id;
run;
Thank you. I've been able to make this work. Is there away to adapt it for multiple variables in one step? In other words, I'd like to get the total count for 'var1', 'var2', etc. by ID.
proc summary nway data=have;
class id;
var var1 var2 var3; /* Or use var var1-var3; if the names have consecutive suffix numbers */
output out=sums sum=/autoname;
run;
data want;
merge have sums;
by id;
run;
I prefer SQL here.
proc sql;
create table want as
select *, sum(var1) as totalcount
from have
group by id;
quit;
@mt88 wrote:
Hello, I'm looking for a way to create a variable that will give me the total count for another variable for each participant ID. For example, If I have 'var1' in the original dataset:
ID var1 1 0 1 . 1 1 1 0 1 1 1 . 1 1 1 0 1 1 1 0 2 0 2 1 2 . 2 0 2 0 2 1 2 1
I'd end up with a new variable 'totalcount':
ID var totalcount 1 0 4 1 . 4 1 1 4 1 0 4 1 1 4 1 . 4 1 1 4 1 0 4 1 1 4 1 0 4 2 0 3 2 1 3 2 . 3 2 0 3 2 0 3 2 1 3 2 1 3
Thank you.
@Reeza wrote:
I prefer SQL here.
While I agree that in this case SQL is less typing and conceptually simpler, once you start getting into more real world problems, where you have 5 variables and you not only want the sum but the mean and minimum and maximum and standard deviations, PROC SUMMARY is a much better tool. And so, I would advise people to get used to learning the power of PROC SUMMARY instead of SQL for this type of task.
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.