BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
cxterm
Fluorite | Level 6

Hi all,

Here is a sample dataset with variable A

 

A

1

2

2

1

1

2

2

3

3

2

1

 

Now I want a cnt variable CNT like 

A   CNT

1     2        (since there a 2 '2' just before the next '1') 

2     0        (since there no '3' just before the next '2')

2     0        

1     0

1     3        (there are 3 '2' before the next '1')

2    0

2    2         (there are 2 '3' before the next '2')

3    0

3    0

2    0

1    0

 

How could I got the CNT? Any help? 

Thanks in advance!

1 ACCEPTED SOLUTION

Accepted Solutions
PGStats
Opal | Level 21

You can do this counting with random access:

 

data want;
set have nobs=nobs;
cnt = 0;
do point = _n_+1 to nobs until(_a = a);
    set have (rename=(a=_a)) point=point;
    cnt = cnt + (_a = a + 1);
    end;
drop _a;
run;
PG

View solution in original post

4 REPLIES 4
PGStats
Opal | Level 21

You can do this counting with random access:

 

data want;
set have nobs=nobs;
cnt = 0;
do point = _n_+1 to nobs until(_a = a);
    set have (rename=(a=_a)) point=point;
    cnt = cnt + (_a = a + 1);
    end;
drop _a;
run;
PG
Ksharp
Super User

Hash Table is my last resort .

 

data have;
input A;
cards;
1
2
2
1
1
2
2
3
3
2
1
;
data have;
 set have ;
 by a notsorted;
 group+first.a;
run;
data want;
 if _n_=1 then do;
  if 0 then set have(rename=(a=_a));
  declare hash h(dataset:'have(rename=(a=_a))',multidata:'y');
  h.definekey('group');
  h.definedata('_a');
  h.definedone();
 end;
set have;
by group;
count=0;
if last.group then do;
  _group=group+1;
  rc=h.find(key:_group);
  do while(rc=0);
    if _a=a+1 then count+1;
    rc=h.find_next(key:_group);
  end;
end;
drop _: rc group;
run;
proc print;run;
cxterm
Fluorite | Level 6

It also works although I select the way a little codings. Thank you!

sas-innovate-2024.png

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.

 

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 4 replies
  • 1167 views
  • 1 like
  • 3 in conversation