BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
moreka
Obsidian | Level 7

How could I create new observations in a dataset based on adding, subtracting, etc. across other observations?

In the example below, observation 4 is created so that

Var1 = 'NotTN'

Var2 = sum of all Var2 where Var1^='TN'

Have:

Var1Var2
SC1
NC3
TN5

Want:

Var1Var2
SC1
NC3
TN5
NotTN4

Thanks!

1 ACCEPTED SOLUTION

Accepted Solutions
Reeza
Super User

It depends. How complex can your rules get? That one is fairly straight forward, and here's a hard coded solution. If you need something that changes with your data dynamically this won't work.

data want;

set have end=eof;

retain sum;

if var1 ne 'TN' then sum=sum+var2;

output;

if eof then do;

var1='NotTN';

var2=sum;

output;

end;

run;

View solution in original post

3 REPLIES 3
Reeza
Super User

It depends. How complex can your rules get? That one is fairly straight forward, and here's a hard coded solution. If you need something that changes with your data dynamically this won't work.

data want;

set have end=eof;

retain sum;

if var1 ne 'TN' then sum=sum+var2;

output;

if eof then do;

var1='NotTN';

var2=sum;

output;

end;

run;

moreka
Obsidian | Level 7

Thanks!  The 'end=' option is exactly what I'm looking for. 

Also, I needed to put a 0 at the end of the retain line to work:

     retain sum 0;

stat_sas
Ammonite | Level 13

Using sql

data have;
input var1 $ var2;
if var1='TN' then flag=1; else flag=0;
datalines;
SC 1
NC 3
TN 5
;

proc sql;
select var1,var2 from have
union
select "NotTN",sum(var2) from have
where flag=0
order by var2;
quit;

sas-innovate-2024.png

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.

 

Register now!

How to Concatenate Values

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 3 replies
  • 812 views
  • 0 likes
  • 3 in conversation