我正在尝试从文本文件创建SAS数据集。文本文件以完全相同的格式显示数据:
-HEADER HEADER HEADER
-HEADER HEADER HEADER
April SpringRace男性
$$$$$$$$$$$$$$$$$$$$
名称年龄状态/这些是文本文件/
中的标题$$$$$$$$$$$$$$$$$$$$
John Smith 30 CA
Mark Doe 49 TX
可能是SpringRace2女性
$$$$$$$$$$$$$$
姓名年龄状态
$$$$$$$$$$$$$$
Betty White 50 ME
Jane Smith 37 NY
我正在完成数据步骤的问题是:绕过不同的标题行,然后收集"事件" ******标题*******之前的数据作为变量然后跳过 标题 并为实际人员分配变量。整个巨大的文本文件中的格式类似。请有人能指出我正确的方向吗?
我一直在试验: 数据工作。测试; infile c:\ tester dlm =' ,$' missover; 输入/ / /月15美元。 EventName $ 15。性别$ 6。 (这是我被卡住的地方,因为我不知道如何跳过"名称年龄状态"在文本文件中,只是将变量分配给" John Smith 30 CA"等等) 运行;
我还认为必须有更好的方法来传递标题,因为不确定它们总是只有2行。
由于
答案 0 :(得分:0)
我认为使用@' my_char_string' INPUT语句中的列指针可以帮助您,如果分隔数据值的标题总是重复,并且您知道它们是什么。例如:
INFILE mydatafile FLOWOVER FIRSTOBS = 2;
INPUT month $ race $ sex $ @' State' first_name $ last_name $ address $;
INFILE语句中的FIRSTOBS = 2选项跳过HEADER HEADER ...行,FLOWOVER选项告诉SAS继续在下一行查找数据,特别是@' State'。您可能需要指定其他选项和格式,具体取决于您的输入文件格式,分隔符等。
根据您的编辑,您可以使用月份值来确定您正在阅读事件的开始,然后使用尾随@,保留和一些条件逻辑,在单独的行中读取您的参与者并保留事件信息在这些参与者之间(只需在第一个if子句中添加所有剩余的月份名称):
data test1;
length test $20 month $20 event $20 gender $20 firstname $20 lastname $20 state $2;
infile "test1.txt" DLM=' $' FIRSTOBS=5;
retain month event gender; * Keep these values from last readin;
input test $ @; /* Read in the first word in the data line being
read into test var, and stay on this line for
now (with @)*/
if strip(test) in('April', 'May') then do; /* If test var contains month,
then read in all of the variables,
and skip the name/age/state titles row*/
input @1 month $ event $ gender $ @'State' firstname $ lastname $ age state $ ;
end;
else do; /* Otherwise, the data line being read in should contain
only names, age and state, so read in those values only.
The month, event and gender values will be kept the same
by the retain statement above.*/
input @1 firstname $ lastname $ age state $ ;
end;
drop test; /* Comment out this drop statement to see whats in test var*/
run;
此代码适用于每个事件的不同数量的参与者。但是为了使这段代码能够运作,这个月不能错过。
有用的提示:要查看SAS正在读取的当前数据行中的内容,请尝试添加
put _INFILE_;
在INFILE语句之后。它会按照SAS看到的方式将数据行打印到您的日志中。
答案 1 :(得分:0)
希望你很久以前解决了你的问题,但这是另一个建议。 在输入语句上使用尾随@可以应用第二个输入语句,这将是首选解决方案。这个解决方案并没有真正使用尾随@,但是我把它留给了你将来考虑。
DATA test;
INFILE 'stacktest.txt' lrecl=200 missover;
length n1 n2 n3 n4 $20. ;
input @1 c1 $1. @1 c2 $2. @1 c5 $5. @1 lne & $75. @ ;
keep month event gender fname lname age state;
if c1 = ' ' then return;
if c1 = '-' then return;
if c1 = '$' then return;
if c5 = 'Name' then return;
n1 = scan(lne, 1);
n2 = scan(lne, 2);
n3 = scan(lne, 3);
n4 = scan(lne, -1);
if ( n3 eq 'Male' or n3 eq 'Female') then do;
month = n1 ;
event = n2;
gender = n3 ;
return;
end;
else do ;
* input fname $ lname $ age state $ ;
fname = n1 ;
lname = n2 ;
age = n3 ;
state = n4 ;
output;
end;
retain month event gender;
run;