itzy
itzy

Reputation: 11765

Read wide file with repeated variables in SAS

I have input data shaped like this:

var1 var2 var3 var2 var3 ...

where each row has one value of var1 followed by a varying number of var2-var3 pairs. After reading this input, I want the data set to have multiple records for each var1: one record for each pair of var2/var3.

So if the first two lines of the input file are

A 1 2 7 3 4 5
B 2 3

this would generate 4 records:

A 1 2
A 7 3
A 4 5
B 2 3

Is there an simple/elegant way to do this? I've tried reading each row as one long variable and splitting with scan but it's getting messy and I'm betting there's a really easy way to do this.

Upvotes: 0

Views: 120

Answers (2)

Dmitry Shopin
Dmitry Shopin

Reputation: 1763

Like this (conditional input with jumping back):

data test;
infile datalines missover;
input var1 $ var2 $ var3 $ temp $ @;
output;
do while(not missing(temp));
    input  +(-2) var2 $  var3 $ temp $ @;
    output;
end;
drop temp;
datalines;
A 1 2 7 3 4 5
B 2 3
;
run;

Upvotes: 1

BellevueBob
BellevueBob

Reputation: 9618

I'm sure there are many ways to do this, but here is the first that comes to my mind:

data want(keep=var1 var2 var3);
  infile 'path-to-your-file';
  input;
  var1 = input(scan(_infile_,1),$8.);
  i = 1;
  do while(i ne 0);
     i + 1;
     var2 = input(scan(_infile_,i),8.);
     i + 1;
     var3 = input(scan(_infile_,i),8.);
     if var3 = . then i = 0;
     else output;
     end;
run;

_infile_ is an automatic SAS variable that contains the currently read record. Use an appropriate informat for each variable you read.

Upvotes: 1

Related Questions