Hi,
I am merging two data sets and I am creating two Vars based on the first. last. by groups. Everything is merging fine, the newly created Vars and totaling fine, but my output is only displaying the totals or rather the final observation from each by group. I would like all the observations within each by group displayed in addition to the total and I know there is a way to do this but I can not find it in my notes or online anywhere.
My code is pretty basic:
Data set;
merge one two;
by animal name age;
if first.age then do;
totpounds=0;
end;
totpounds+pounds;
if last.age output;
run;
These are dummy Vars but basically that's the idea. Any help would truly be appreciated.
Thank you!
What do you mean by total on each observation, do you mean incremental, or sum() all on every line? For incremental you can do it in the one step:
data want; merge one two; by animal name age; totpounds=ifn(first.age,pounds,totpounds+pounds); run;
If you want the total on each row, then do that in a separate step and merge back e.g:
proc sql; create WANT as select A.*, B.TOT from HAVE A left join (select AGE,sum(POUNDS) as TOT from HAVE group by AGE) B on A.AGE=B.AGE; quit;
@kmj636 wrote:
Hi,
... but my output is only displaying the totals or rather the final observation from each by group ...
That is happening because you are telling SAS to only ouptut the final observation from each group.
If you take out the statement
if last.age then output;
then it won't happen.
I really apologize and appreciate your view and time. Yes, it should be and is "then output."
I am still not able to see the contributing observations to the totals from the by groups.
@kmj636 wrote:
I really apologize and appreciate your view and time. Yes, it should be and is "then output."
I am still not able to see the contributing observations to the totals from the by groups.
Even though your code was incorrect and omitted the word "then", if you remove this line entirely, you will see the contributing observations.
What do you mean by total on each observation, do you mean incremental, or sum() all on every line? For incremental you can do it in the one step:
data want; merge one two; by animal name age; totpounds=ifn(first.age,pounds,totpounds+pounds); run;
If you want the total on each row, then do that in a separate step and merge back e.g:
proc sql; create WANT as select A.*, B.TOT from HAVE A left join (select AGE,sum(POUNDS) as TOT from HAVE group by AGE) B on A.AGE=B.AGE; quit;
You are wonderful! Thank you so much.
Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.
Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
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.