Hi, I am a new SAS user and I use SAS 9.4. I have a data set like this:
id numbers
1001 1
1001 1
1001 1
1001 1
1002 1
1002 1
1003 1
1003 1
1003 1
...
I hope to collapse like this:
id sum_numbers
1001 4
1002 2
1003 3
I searched some info and I used the following codes which works:
PROC MEANS DATA=have;
CLASS id;
VAR numbers;
OUTPUT OUT=have2 sum= ;
RUN;
However, it is not in the data set anymore. SAS gives me another seperate result table in a seperate window. So I am wondering if there is any magic code in the data step that can keep the results still as part of the dataset?
Thank you!
SQL can. It essentially requires merging the original with the summary data step.
This will generate a message in the log. You can do it in a data step but the code is more complex.
Proc sql;
create table want as
select *, sum(numbers) as sum_numbers
from have
group by id;
quit.
The results that you described do not keep the sums in the data set. You sketched out a separate data set. What would you like the result to look like?
SQL can. It essentially requires merging the original with the summary data step.
This will generate a message in the log. You can do it in a data step but the code is more complex.
Proc sql;
create table want as
select *, sum(numbers) as sum_numbers
from have
group by id;
quit.
SQL can. It essentially requires merging the original with the summary data step.
This will generate a message in the log. You can do it in a data step but the code is more complex.
Proc sql;
create table want as
select *, sum(numbers) as sum_numbers
from have
group by id;
quit.
data datas;
input Id numbers;
datalines;
1001 1
1001 1
1001 .
1001 1
1002 1
1002 .
1003 1
1003 1
1003 1
run;
proc sort data=datas
out=datas;
by Id;
run;
data sumbygroup (drop=numbers);
set datas;
by Id;
if first.Id then do; sum=numbers; count=1;end;
else do; sum+numbers; count+1;end;
if last.Id then output;
run;
proc print data=sumbygroup;
run;
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.