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!

SAS Innovate 2025: Call for Content

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!

Submit your idea!

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.

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
  • 6 replies
  • 3025 views
  • 6 likes
  • 5 in conversation