The little SAS book 学习笔记
2.1 导入数据到 SAS 的办法
直接输入
利用文件创建
其他软件数据文件转化,比如 Stata 的 dta
直接读取其他软件数据文件
2.2 使用 VIEWTABLE 窗口输入数据不建议
2.3 使用导入向导读取文件第一步
如果要导入 csv 就选择下面那行
第二步
第三步
第四步
第五步
2.4 指定原始数据位置内部原始数据
使用 CARD 语句创建数据集
1234567891011DATA 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 语句
12345DATA Presidents; INFILE './training/data/Presidents.txt' LRECL=2000; INPUT President $ Party $ Number; PUT President= Party= Number=;RUN;
2.5 读取空格分隔的原始数据我们现在导入一个叫做 ToadJump 的数据
1234567Lucky 2.3 1.9 . 3.0Spot 4.6 2.5 3.1 .5Tubs 7.1 . . 3.8Hop 4.5 3.2 1.9 2.6Noisy 3.8 1.3 1.8 1.5Winner 5.7 . . .
可以看到,第五行的数据串行了,那么 SAS 能否准确读取呢?
12345678DATA 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 的日志中也记录了这一个事件
这里注意一个细节,代码中用了 $ 声明 ToadName 的变量类型为字符型,而数值型则不需要特别声明
2.6 读取按列排列的原始数据其实就是按照列长度和范围读取变量
代码操作:
12345678DATA 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 代表小数位数
代码示例
数据文件:
123456Alicia Grossman 13 c 10-28-2012 7.8 6.5 7.2 8.0 7.9Matthew Lee 9 D 10-30-2012 6.5 5.9 6.8 6.0 8.1Elizabeth Garcia 10 C 10-29-2012 8.9 7.9 8.5 9.0 8.8Lori Newcombe 6 D 10-30-2012 6.7 5.6 4.9 5.2 6.1Jose Martinez 7 d 10-31-2012 8.9 9.510.0 9.7 9.0Brian Williams 11 C 10-29-2012 7.8 8.4 8.5 7.9 8.0
代码文件:
12345678DATA 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 混合的输入样式示例数据
12345Yellowstone ID/MT/WY 1872 4,065,493Everglades FL 1934 1,398,800Yosemite CA 1864 760,917Great Smoky Mountains NC/TN 1926 520,269Wolf Trap Farm VA 1966 130
示例代码
1234567DATA 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表示告知数据里用了逗号做千位分隔符
2.10 读取杂乱的原始数据