UCLA Academic Technology Services HomeServicesClassesContactJobs
Search

SAS Code Fragments
Reading Hierarchical Data

The file contains a "dad" record, and one or more "kid" records.  The "dad" is the master record, and the kids are the subsequent records.  In this example, there is a variable called "rectype" that tells us if it is a "dad" record, or a "kid" record.  I hope your file has some kind of indicator that tells you what type of record you have .  For example, perhaps having any data in column 4 means you have a master record, and nothing in column 4 means a subsequent record.  The first input statement reads the variable to tell us if we have a master or subsequent record, and it MUST end with an @ sign, which holds the record so we can read it again.  If it is a "dad" record, then we read the dad data (see the input for that).  Note, we then have a retain statement that retains all of the variables from the master record.  If it is a "kid" record, then we read the kids data, and then output the record.  If it is neither a kid nor a dad (perhaps an error?) then input the line, and PUT a message to the log indicating a problem.

Data dadkid;
  * find out what kid of record this is.  The ;
  * @ at the end of the line saves the record to be read again ;

  INPUT @1 rectype $1. @ ;

  * if it is a "dad" input the dad info ;

  IF (rectype = "D") THEN INPUT @3 dfamid @5 dadname $4. @10 dadinc ;

  * retain all dad variables ;

  RETAIN dfamid dadname dadinc ;

  * if it is a "kid" input the kid info and output the record ;

  IF (rectype = "K") THEN
  DO;

    INPUT @3 kfamid @5 kidname $4. @10 birth @12 age @14 wt @17 sex $1. ;

    OUTPUT;

  END;

  * check to see if not a kid, not a dad;

  IF (rectype NE "D") and (rectype NE "K") THEN

  DO;

    INPUT;

    PUT "Bad Record Fouind. Not a kid, not a dad";

  END;

CARDS;

D 1 Bill 30000
K 1 Beth 1 9 60 f
K 1 Bob  2 6 40 m
K 1 Barb 3 3 20 f
D 2 Art  22000
K 2 Andy 1 8 80 m
K 2 Al   2 6 50 m
K 2 Ann  3 2 20 f
D 3 Paul 25000
K 3 Pete 1 6 60 m
K 3 Pam  2 4 40 f
K 3 Phil 3 2 20 m
;
RUN;

PROC PRINT DATA=dadkid;
RUN;

How to cite this page

Report an error on this page

UCLA Researchers are invited to our Statistical Consulting Services
We recommend others to our list of Other Resources for Statistical Computing Help
These pages are Copyrighted (c) by UCLA Academic Technology Services


The content of this web site should not be construed as an endorsement of any particular web site, book, or software product by the University of California