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..
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;
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;
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
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;
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
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;
Thanks for the quick and correct answers!
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 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.