DATA uspresidents; INPUT Presidents $ Party $ Number; CARDS; Adams F 2 Lincoln R 16 Grant R 18 Kennedy D 35 ; RUN; PROC PRINT DATA = uspresidents; RUN;
外部数据文件
使用 INFILE 语句
1 2 3 4 5
DATA Presidents; INFILE'./training/data/Presidents.txt' LRECL=2000; INPUT President $ Party $ Number; PUT President= Party= Number=; RUN;
DATA toads; INFILE'./training/data/ToadJump.dat'; INPUT ToadName $ Weight Jump1 Jump2 Jump3; /* Specify variables' names */ /* Notice the log: NOTE: SAS went to a new line when INPUT statement reached past the end of a line. */ RUN; PROC PRINT DATA = toads; TITLE'SAS Data Set Toads'; /* Specify title of result table */ RUN;
可以看到,只要当前行数低于变量数,那么 SAS 就会继续将下一行数据读取为变量值,SAS 的日志中也记录了这一个事件
DATA teams; INFILE'./training/data/OnionRing.dat'; INPUT VisitingTeam $ 1-20 ConcessionSales 21-24 BleacherSales 25-28 OurHits 29-31 TheirHits 32-34 OurRuns 35-37 TheirRuns 38-40; RUN; PROC PRINT DATA = teams; TITLE'SAS Data Set Sales'; /* Specify title of result table */ RUN;
2.7 读取非标准格式数据
SAS 会将读取的日期转化为距离 1960 年 1 月 1 日的天数
一共有三种输入格式基本类型:
字符
数值
日期
$informatw.
informatw.d
informatw.
$ 的作用是声明字符型,前面已经提过
w 表示 width,字符或者数值的宽度
d 代表小数位数
代码示例
数据文件:
1 2 3 4 5 6
Alicia Grossman 13 c 10-28-2012 7.8 6.5 7.2 8.0 7.9 Matthew Lee 9 D 10-30-2012 6.5 5.9 6.8 6.0 8.1 Elizabeth Garcia 10 C 10-29-2012 8.9 7.9 8.5 9.0 8.8 Lori Newcombe 6 D 10-30-2012 6.7 5.6 4.9 5.2 6.1 Jose Martinez 7 d 10-31-2012 8.9 9.510.0 9.7 9.0 Brian Williams 11 C 10-29-2012 7.8 8.4 8.5 7.9 8.0
代码文件:
1 2 3 4 5 6 7 8
DATA content; INFILE'./training/data/Pumpkin.dat'; INPUT Name $16. Age 3. +1 Type $UPCASE1. +1 Date MMDDYY10. (Score1 Score2 Score3 Score4 Score5) (4.1); /* Max for char is 32767, default is 8 */ RUN; PROC PRINT DATA = content; TITLE'Pimpkin Carving Content'; /* Specify title of result table */ RUN;
其中,代码的 +1 表示跳过一列
4.1 表示所有的数值 Score 都是保留一位小数,所以在 9.510.0 处可以精准识别
2.8 常见输入格式
2.9 混合的输入样式
示例数据
1 2 3 4 5
Yellowstone ID/MT/WY 1872 4,065,493 Everglades FL 1934 1,398,800 Yosemite CA 1864 760,917 Great Smoky Mountains NC/TN 1926 520,269 Wolf Trap Farm VA 1966 130
示例代码
1 2 3 4 5 6 7
DATA nationalparks; INFILE'./training/data/NatPark.dat'; INPUT ParkName $ 1-22 State $ Year @40 Acreage COMMA9.; /* @40 means the cursor move to 40 col */ RUN; PROC PRINT DATA = nationalparks; TITLE'Selected National Parks'; /* Specify title of result table */ RUN;
解释
ParkName 的输入格式为字符,列范围为 1-22,这是因为它中间有空格
State 指定为字符,没有空格,直接输入即可
Year 和 Acreage 没有指定,默认为数值型
中间的 @40 表示读取位置跳到第 40 列
COMMA9. 告知 SAS 读取 9 列,即使是空白也会读取,COMMA表示告知数据里用了逗号做千位分隔符