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!
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.