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

I have monthly data on variable x across 20 countries and would like to sum only the negative values of the variable per month. I've used the code below to sum all of the monthly observations across 20 countries together, and would like to know how to modify the code to get it to sum only the negative values.

data want;

  set have;

  by date;

  if first.date then total=0;

  total+x;

  if last.date then output;

run;

thanks in advance..

1 ACCEPTED SOLUTION

Accepted Solutions
Linlin
Lapis Lazuli | Level 10

more efficient:

data want;

set have(where=(x<0));

by date;

if first.date then total=0;

total+x;

if last.date then output;

run;

View solution in original post

6 REPLIES 6
Gerd47
Calcite | Level 5

Try this

data have;

input date x;

cards;

1 3

1 -3

1 -4

2 4

2 -2

2 -7

;

run;

data want;

set have;

by date;

if first.date then total=0;

if x<0 then total+x;

if last.date then output;

run;

Haikuo
Onyx | Level 15

Or use (where=) to make it more efficient in this case:

data want;

set have(where=(x<0));

by date;

if x<0;

if first.date then total=0;

if x<0 then total+x;

if last.date then output;

run;

Regards,

Haikuo

Linlin
Lapis Lazuli | Level 10

more efficient:

data want;

set have(where=(x<0));

by date;

if first.date then total=0;

total+x;

if last.date then output;

run;

Haikuo
Onyx | Level 15

LOL, I don't know what I am doing. Guess I just added (where=) to his/her code harmlessly and more important,  effortlessly. Linlin, thanks for pointing that out.

Haikuo

Howles
Quartz | Level 8

I don't know if efficiency is a concern. I do know that the WHERE approach will not generate an observation for a month with no negatives. That may or may not be desired.

Linlin wrote:

more efficient:

data want;

set have(where=(x<0));

by date;

if first.date then total=0;

total+x;

if last.date then output;

run;

carbs
Calcite | Level 5

Thanks for the quick and correct answers!

hackathon24-white-horiz.png

2025 SAS Hackathon: There is still time!

Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!

Register Now

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 6 replies
  • 3740 views
  • 6 likes
  • 5 in conversation