## Help with Retain

Solved
Super Contributor
Posts: 506

# Help with Retain

Hello Everyone,

I want to group observation anytime variable "time" in my data reach value 1 and group=group +1

So basically, the Want file should be the original added 1 more variable name group as below.

1 2 1

2 3 1

3 2 1

1 6 2

2 9 2

3 6 2

4 9 2

1 9 2

2 1 3

3 1 3

I guess the retain should be used but I am not sure how to get the result I want.

Any help is very much appreciated.

Have a nice weekend.

HHC

data want;

input time value;

datalines;

1 2

2 3

3 2

1 6

2 9

3 6

4 9

1 9

2 1

3 1

;run;

Accepted Solutions
Solution
‎11-09-2013 07:15 AM
Posts: 1,147

## Re: Help with Retain

The code of sir Arthur is good. Here is just an alternative.

data have;

input time value;

order=_n_;

datalines;

1 2

2 3

3 2

1 6

2 9

3 6

4 9

1 9

2 1

3 1

;

run;

proc sort data=have;

by  time ;

run;

data want;

set have;

retain count;

by time;

if first.time then count=1;

else count+1;

run;

proc sort data=want;

by order;

run;

Thanks,

Thanks,
Jag

All Replies
PROC Star
Posts: 8,163

## Re: Help with Retain

You weren't very clear about what you are trying to accomplish, thus I'll just guess:

data have;

input time value;

datalines;

1 2

2 3

3 2

1 6

2 9

3 6

4 9

1 9

2 1

3 1

;

run;

data want;

set have;

if _n_ eq 1 then group=1;

if time lt lag(time) then group+1;

run;

Super Contributor
Posts: 644

## Re: Help with Retain

hhchenfx

Where Art uses group + 1 that implies the statement (automatically)

retain group ;

Richard

Solution
‎11-09-2013 07:15 AM
Posts: 1,147

## Re: Help with Retain

The code of sir Arthur is good. Here is just an alternative.

data have;

input time value;

order=_n_;

datalines;

1 2

2 3

3 2

1 6

2 9

3 6

4 9

1 9

2 1

3 1

;

run;

proc sort data=have;

by  time ;

run;

data want;

set have;

retain count;

by time;

if first.time then count=1;

else count+1;

run;

proc sort data=want;

by order;

run;

Thanks,

Thanks,
Jag
Super Contributor
Posts: 506

## Re: Help with Retain

I got it.

Have a nice weekend.

HHC

🔒 This topic is solved and locked.