Auto-suggest helps you quickly narrow down your search results by suggesting possible matches as you type.

Showing results for

Find a Community

- Home
- /
- SAS Programming
- /
- General Programming
- /
- How to extract the first negative or next positive...

- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page

- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Highlight
- Email to a Friend
- Report Inappropriate Content

04-17-2012 02:38 PM

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

- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Highlight
- Email to a Friend
- Report Inappropriate Content

Posted in reply to imcbczm

04-17-2012 03:16 PM

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;

All Replies

Solution

04-17-2012
03:16 PM

- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Highlight
- Email to a Friend
- Report Inappropriate Content

Posted in reply to imcbczm

04-17-2012 03:16 PM

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;

- Mark as New
- Bookmark
- Subscribe
- Subscribe to RSS Feed
- Highlight
- Email to a Friend
- Report Inappropriate Content

Posted in reply to Reeza

04-17-2012 03:33 PM

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