Calcite | Level 5

## Return a total for a given variable by ID

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.

1 ACCEPTED SOLUTION

Accepted Solutions
Diamond | Level 26

## Re: Return a total for a given variable 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;``````
--
Paige Miller
5 REPLIES 5
Diamond | Level 26

## Re: Return a total for a given variable by ID

``````proc summary nway data=have;
class id;
var var1;
output out=sums sum=totalcount;
run;
data want;
merge have sums;
by id;
run;``````
--
Paige Miller
Calcite | Level 5

## Re: Return a total for a given variable by ID

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.

Diamond | Level 26

## Re: Return a total for a given variable 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;``````
--
Paige Miller
Super User

## Re: Return a total for a given variable by ID

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.

Diamond | Level 26

## Re: Return a total for a given variable by ID

@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.

--
Paige Miller
Discussion stats
• 5 replies
• 564 views
• 2 likes
• 3 in conversation