How to extract the first negative or next positive value in a block of data

Accepted Solution Solved
Reply
Contributor
Posts: 39
Accepted Solution

How to extract the first negative or next positive value in a block of data

I want to get the first negative number or last positive number in each block of negative or positive data, such as this. Can anybody help? Thanks,

data test;

input x;

datalines;

-1

-2

-3

-4

2

3

1

7

2

-8

-2

-10

4

8

2

9

;

run;


Accepted Solutions
Solution
‎04-17-2012 03:16 PM
Super User
Posts: 17,963

Re: How to extract the first negative or next positive value in a block of data

I'm sure there's a way to do this in one step using the lag function, but I'm guessing you have other variables that you're going to want to keep not just these numbers.

You'll need to verify the logic for 0 values if they come up.

Here's a two part simple solution.

*Identify positive negative groups;

data want;

    set test;

    if x<0 then group='N';

    else group='P';

run;

data want2;

    set want;

    by group notsorted; *Not sorted to keep data in order it is;

    if group='N' and first.group then output;*Output first of negative groups;

    if group='P' and last.group then output;*Output last of positive groups;

run;

View solution in original post


All Replies
Solution
‎04-17-2012 03:16 PM
Super User
Posts: 17,963

Re: How to extract the first negative or next positive value in a block of data

I'm sure there's a way to do this in one step using the lag function, but I'm guessing you have other variables that you're going to want to keep not just these numbers.

You'll need to verify the logic for 0 values if they come up.

Here's a two part simple solution.

*Identify positive negative groups;

data want;

    set test;

    if x<0 then group='N';

    else group='P';

run;

data want2;

    set want;

    by group notsorted; *Not sorted to keep data in order it is;

    if group='N' and first.group then output;*Output first of negative groups;

    if group='P' and last.group then output;*Output last of positive groups;

run;

Contributor
Posts: 39

Re: How to extract the first negative or next positive value in a block of data

Wonderful, I got the idea. The key is 'notsorted' and then you can identify the first and last in each block!

thanks a lot!

Z

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 2 replies
  • 716 views
  • 0 likes
  • 2 in conversation