We’re smarter together. Learn from this collection of community knowledge and add your expertise.

search a tree to get households

by Super User on ‎12-25-2014 02:03 AM - edited on ‎10-05-2015 03:35 PM by Community Manager (383 Views)

Details is

 

Make it better .

 

 

data Forms;
input FormID $ Parent $ Child $ @@;
cards;
1  1 .  
1  1 2   1  2 20 1 20 200
1  1 3   1  3 30 1 30 300   1 300 3000
2  9  .
2  9 4   2  4 5   2  4 6   2   6 5000
2  6 7   2  7 8   2  6 400 2   6 4000
2  6 10 2  6 11   2 6  12
;
run;


data check;
 set forms ;
 P=Child;C=Parent; 
 drop Parent Child;
run;
data temp(keep= path);
if _n_ eq 1 then do;
length path _path  $ 400 ;

if 0 then set check;
declare hash ch(hashexp:20,dataset:'check(where=(P is not missing))');
ch.definekey('FormID','P');
ch.definedone();

if 0 then set Forms;
declare hash ha(hashexp:20,dataset:'Forms(where=(child is not missing))',multidata:'Y');
ha.definekey('FormID','Parent');
ha.definedata('Child');
ha.definedone();

declare hash pa(ordered:'Y');
declare hiter hi_path('pa');
pa.definekey('count');
pa.definedata('path');
pa.definedone();
end;

set Forms(where=(child is not missing));
count=1;
path=catx(' ',FormID,Parent,Child); 
pa.add();
do while(hi_path.next()=0);
_path=path;  
FormID=scan(path,1,' ');
P=scan(path,2,' ');
Parent=scan(path,-1,' '); 
rc=ha.find();
if (rc ne 0 or (rc eq 0 and find(path,strip(Child)))) and ch.check() ne 0 then output; 
 do while(rc=0);
  if not find(path,strip(Child)) then do;
                                      count+1;
                                      path=catx(' ',path,Child);
                                      pa.add(); 
                                      path=_path;
                                        end;
                                        
  rc=ha.find_next();
 end;
end;
pa.clear();
run;
data want(keep=want);
 set temp;
 length want $ 400;
 do i=1 to countw(path);
   if i=1 then want=catx(' ',want,cats('FID-',scan(path,i,' ')));
    else if i=2 then want=catx(' ',want,cats('P-',scan(path,i,' ')));
      else  if i=3 then want=catx(' ',want,cats('C-',scan(path,i,' ')));
       else  want=catx(' ',want,cats('G',i-3,'C-',scan(path,i,' ')));
 end;
run;




 

 

 

 

Xia Keshan

Your turn
Sign In!

Want to write an article? Sign in with your profile.


Looking for the Ask the Expert series? Find it in its new home: communities.sas.com/askexpert.