Solved
Contributor
Posts: 44

# Summing only negative values of a certain variable

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;

Accepted Solutions
Solution
‎04-02-2012 08:17 AM
Super Contributor
Posts: 1,636

## Re: Summing only negative values of a certain variable

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;

All Replies
Occasional Contributor
Posts: 10

## Summing only negative values of a certain variable

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;

Posts: 3,167

## Summing only negative values of a certain variable

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

Solution
‎04-02-2012 08:17 AM
Super Contributor
Posts: 1,636

## Re: Summing only negative values of a certain variable

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;

Posts: 3,167

## Re: Summing only negative values of a certain variable

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

Regular Contributor
Posts: 184

## Re: Summing only negative values of a certain variable

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;`
Contributor
Posts: 44

## Summing only negative values of a certain variable

Thanks for the quick and correct answers!

🔒 This topic is solved and locked.