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.
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.