University of Rochester Medical Center
SearchDirectoryNewsEventsStrong HealthURMC Home

SAS Helpful Hints

A quick method to read in fixed field data.

Problem: Reading data from a file usually requires that you specify which variables are to be read from which columns. This is a tedious process and I do not have time to sit around counting columns.

Solution: Create an array of variables and a corresponding array of their lengths. Input each line of data as one long character string and loop through the arrays to substring the data into individual variables.

With this template you may read several data files quickly by changing the array definitions and filename.

Title1 "Reading in Data";
Libname save 'C:\MyData';

Filename in1 'sample.dat';
Data work.A;
    Infile in1 N=1 Missover Delimiter='~' Linesize=500;
    Length aline $500.;
    *List of variables to input;
    Array variables id v1-v10;
    *Lengths of variables to input;
    Array lengths{11} (4 6 2 10 2 2 1 12 2 4 4);
    Input aline;
    p=1; *Start pointer at first column;
    Do i=1 To Dim(variables);
        variables{i}=0+Substr(aline,p,lengths{i});
        *Exceptions for character variables:;
        If i=4 Then c1=Substr(aline,p,lengths{i});
        If i=8 Then c2=Substr(aline,p,lengths{i});
        p=p+lengths{i}; *Increment pointer;
    End;
    Keep id v1-v10 c1 c2;
Run;

Please send your comments and suggestions about this web page to A. Watts (watts@bst.rochester.edu)