DATA Step, Macro, Functions and more

Explanation for code - reading a text file

Reply
Occasional Contributor
Posts: 10

Explanation for code - reading a text file

[ Edited ]

for given data:

 

11 john  1 77
11 88    2 james
22 bobby 1 55
22 89    2 opey

 

question.JPG

 

also , i coded as follows, though program works perfect, but I want to know why ((then input @1 id @4 score @12 name $5. @12 name $5. @10 source 1.Smiley Wink) requires direct pointing , even id variable requires it?

 

 

dm"log;clear;output;clear";

DATA result2;
input @10 source 1.@; *recording in input buffer source ;

if source = 1 then input @1 id @4 name $5. @12 score @12 score @10 source 1. ;
if source = 2 then input @1 id @4 score @12 name $5. @12 name $5. @10 source 1.;

datalines;
11 john  1 77
11 88    2 james
22 bobby 1 55
22 89    2 opey
;

RUN;

PROC PRINT data = result2 noobs;
var source id name score;
RUN;



[Edit by Kurt Bremser] Moved program text to code window, corrected datalines so they match the input statement column pointers


question.JPG
Super User
Posts: 6,928

Re: Help please

After the first input statement, that stays in the same input line because of the trailing @, the column pointer stays where it was after reading source.

Therefore, the column pointer must be set to the beginning of the line before attempting to read id.

---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
Super User
Posts: 6,928

Re: Explanation for code - reading a text file

PS you could simplify your code like that:

data result2;
input @10 source 1. @1 @; *recording in input buffer source ;
if source = 1 then input id @4 name $5. @12 score @12 score @10 source 1. ;
if source = 2 then input id @4 score @12 name $5. @12 name $5. @10 source 1.;
datalines;
11 john  1 77
11 88    2 james
22 bobby 1 55
22 89    2 opey
;
run;
---------------------------------------------------------------------------------------------
Maxims of Maximally Efficient SAS Programmers
Super User
Posts: 17,776

Re: Explanation for code - reading a text file

You input file a fixed width file so each variable starts at a specified column. Consider how it handles a name such as John Paul. 

It has two layouts sending on source column. I think your input statements for source is incorrect as you read name/score twice. 

Your sample data posted doesn't reflect this because of formatting in forum most likely. 

Ask a Question
Discussion stats
  • 3 replies
  • 220 views
  • 0 likes
  • 3 in conversation