Haikuo,
Say I did want to now have Var_b_2 as another level so now my final dataset looks like the below set. How do you adjust your code for the additional level?
Var_a Var_b Var_b_2 Var_C
0 1 1 1
0 1 2 1
0 2 1 1
0 3 1 1
0 3 5 1
0 3 6 1
1 2 1 2
1 3 1 2
2 3 1 3
3 3 2 1
3 3 5 2
4 1 1 2
4 1 2 2
4 2 1 3
4 3 5 3
It looks to me like you just want to sort by var b and b2 and reset the counter when you see FIRST.B2. Var_A is just an example of an extra variable that you want to carry along. You can extent this logic to as many sort by variables as you want, you still just want to trigger the counter off of the change in the last variable in the list.
%let byvars=var_b var_b2;
proc sort data=have;
by &byvars;
run;
data want;
set have ;
by &byvars;
if first.%scan(&byvars,-1) then var_c=1;
else var_c+1;
run;
Obs var_a var_b var_b2 want_c var_c
1 0 1 1 1 1
2 4 1 1 2 2
3 0 1 2 1 1
4 4 1 2 2 2
5 0 2 1 1 1
6 1 2 1 2 2
7 4 2 1 3 3
8 0 3 1 1 1
9 1 3 1 2 2
10 2 3 1 3 3
11 3 3 2 1 1
12 0 3 5 1 1
13 3 3 5 2 2
14 4 3 5 3 3
15 0 3 6 1 1
Thanks Tom! This worked!
Hi,
Var_a Var_b Var_b_2 Var_C
0 1 1 1
0 1 2 1
0 2 1 1
0 3 1 1
0 3 5 1
0 3 6 1
1 2 1 2
1 3 1 2
2 3 1 3
3 3 2 1
3 3 5 2
4 1 1 2
4 1 2 2
4 2 1 3
4 3 5 3
I am still confused about your rules, so before I am doing anything useless, please explain those three rows. How var_c values that way.
Haikuo
Ok,
data have;
input Var_a Var_b;
cards;
0 1
0 2
0 3
1 2
1 3
2 3
3 3
4 1
4 2
4 3
;
data want;
array t(3) _temporary_;
set have;
do _n_=1 to dim(t);
t(_n_)+(var_b=_n_);
end;
var_c=t(var_b);
run;
proc print;run;
Haikuo
update: using '_n_' to replace 'i'
I coded it a few days ago for another user.
data have; input Var_a Var_b; cards; 0 1 0 2 0 3 1 2 1 3 2 3 3 3 4 1 4 2 4 3 ; run; data want; if _n_ eq 1 then do; declare hash ha(); ha.definekey('var_b'); ha.definedata('count'); ha.definedone(); end; set have; if ha.find()=0 then do; count+1;ha.replace();end; else do;count=1;ha.replace();end; run;
KSharp
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.
Find more tutorials on the SAS Users YouTube channel.