Hi. About 1 years ago, with help of this community, I could complete my project in time. After submit my project, I'm trying to understand the code that several programmers suggested. However, in 'Hash' function, it is hard to understand. https://communities.sas.com/t5/SAS-Programming/cumulative-sum-of-largest-value-of-each-group/m-p/498250#M132362 In this post, I asked how to do sum of largest value of each group cumulatively. Ksharp, Grand advisor of this community, suggested the usage of 'hash' function. I'm reading some posts about 'hash' function and understand the meaning of this function a little. But, there are some difficulties left. Please help the questions i asked below. The code Ksharp suggested is this. data want;
if _n_=1 then do;
if 0 then set have;
declare hash h();
declare hiter hi('h');
h.definekey('clinic');
h.definedata('clinic','count','countsquare');
h.definedone();
end;
set have;
by id;
if first.id then h.clear();
if h.find()=0 then do;count=count+1;countsquare=count**2;h.replace();end;
else do;count=1;countsquare=1;h.replace();end;
_clinic=clinic;_countsquare=countsquare;sum=0;
do while(hi.next()=0);
if _clinic ne clinic then sum+countsquare;
end;
sum+_countsquare ; clinic=_clinic;
drop _:;
run; 1) what is the meaning of '_n_'? if _n_=1 then do;
if 0 then set have; In raw data, there was no 'n' variable. In my knowledge, _n_ may mean starting operations of 'hash' iteration. Then, what is 'if 0'? In first row, _n_ means 1, in this conditions, _n_ must remain '1' but second row, it suddenly became 0. 2) what is the meaning of 'h.find()=0'? if h.find()=0 then do; This is the hardest code to understand. Maybe, the 'find' function means the 'definedata' in hash object, which are 'clinic', 'count' and 'countsquare'. But there was no code to set 'definedata' to zero. 3) what is 'else do'? else do;count=1;countsquare=1;h.replace();end; This means 'h.find() ne 0'. So the definedata in hash object is not 0 which means the total is above zero and this may be not the first row. right? Then, why the 'count' became 1? 4) what is 'do while(hi.next()=0);'? The hi is hiter of hash object. In my knowledge, this mean it import the previous defined hash object, which is 'h'. The 'next' function means the next value in 'definekey' and this mean that do loop until the value in next key become positive. right? 5) what is 'if _clinic ne clinic'? In previous code, '_clinic=clinic;' Ksharp set the '_clinic' variable same with 'clinic' variable. However, in this 'if' funciton, _clinic is not equal to clinic. With previous condition, '_clinic=clinic', there must be no case that _clinic is not equal to clinic. However, this if statement worked well. What is the mechanism?
... View more