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