SAS的基本使用介绍3(数据清洗和加工)

数据导入

导入数据Excel表格

文件->导入数据->选择Excel Workbook选项找到Excel表格导入即可
如果报错可以选择Excel Workbook on PC Files Server导入表格
问题解决:SAS导入Excel数据集时报错:“ERROR: 连接: 没有注册类”

数据合并

纵向合并

利用set语句进行纵向合并

data 数据集;
set 数据集(数据集选项) 数据集(数据集选项);
run;
  • set 数据集(in=临时变量1)
    针对数据集产生一个临时变量,当合并记录属于此集时为1,否则为0
    通常配合if一起使用
  • set 数据集(rename=(原名=新名))
    将两个变量名不同的数据合并
data ab1;
set work.a1 work.b1;
proc print;
run;
data ab1;
set work.a1(rename=(height=ht weight=wt)) work.b1;
proc print;
run;

set后面如果只有一个数据集,此时相当于复制作用,可以保留原数据库,只对新建立的数据集进行操作

横向合并

使用merge语句横向合并

data 数据库;
merge 数据集1 数据集2 数据集3 ...;
by 变量1 变量2;
run;
data ab;
merge ab1 ab2;
by id;
proc print;
run;

by语句相当于指定索引,从而保证连接正常

数据对比

proc compare<base=数据集 compare=数据集> <nosummary> <transpose>;
by 变量1 变量2;
id 变量1 变量2;
run;

数据清洗与查找缺失值

数组

array 数组名[下标]<$><数组元素><(元素初始值)>
array s[5] a b c d e;

查找缺失值

data missing;
set sasuser.xab;
array cha[1] name;
if missing(cha[1]) then output;
array num[10] gender age ht wt time y1-y5;
do i=1 to 10;
if missing(num[i]) then output;
end;
proc print;
run;

删除重复显示的记录

proc sort data=missing out=missing2 nodukey;
by id;
proc print;
run;

自动变量改进

data missing;
set sasuser.xab;
array cha[1] _character_;
if missing(cha[1]) then output;
array num[11] _numeric_;
do i=1 to 11;
if missing(num[i]) then output;
end;
proc print;
run;

继续改进:查找缺失值的万能程序

data missing;
set sasuser.xab;
array cha[*] _character_;
do i=1 to dim(cha);
if missing(cha[1]) then output;
end;
array num[*] _numeric_;
do i=1 to dim(num);
if missing(num[i]) then output;
end;
proc print;
run;

查找异常值
缺失值填补

data xab_revised;
set sasuser.xab;
if id=3 then age=33;
proc print;
run;

proc mi过程来实现缺失值填补

data xab9;
set xab_revised;
run;
proc mi data=xab9 out=nomissing round=1 1 1 minimum=150 1 1 maxmum=200 5 5;
mcmc;
var ht  y2 y4;
run;
proc print data=nomissing;
run;

分析:
out=后面是把数据保存在自定义数据集中;
round=选项的作用是制定填补的小数点位数
mcmc是采用mcmc方法产生随机数
默认产生25个填补完整是数据集,每个数据集的填补值都不同

阶段总结:常见的SAS语句及数据集选项

语句:

input/cards
format
set/merge
if/where
do-end
if-then
drop
keep
delete
length
rename

以上这些SAS语句都可以用于data步中,如果数据使用input输入,那么这些语句通常放在input和cards之间,如果数据利用set复制则放在set语句后

数据集选项:

data newxab;
set sasuser.xab;
rename ht=height;
//where gender =1;
//drop id name;
//Keep gender y1-y5;
run;

数据集选项运行效率更高,作为选项时与set同时作用,作为语句时,是在set语句之后才起作用

产生数据子集

产生特定记录的子集

1.选择具有相同特征的人群子集

data newxab;
set sasuer.xab;
if age<30;
proc print;
run;
data newxab;
set sasuer.xab;
where age<30;
proc print;
run;
data newxab;
set sasuer.xab(where=(age<30));
proc print;
run;

2.选择连续记录的数据子集

proc print data=sasuser.xab(firstobs=1 obs=5);
run;

生成变量子集

选择部分变量生成子集

data newxab;
set sasuer.xab;
keep id y1-y5;
if gender=2;
proc print;
run;
data newxab(keep=id y1-y5);
set sasuer.xab;
if gender=2;
proc print;
run;
data newxab;
set sasuer.xab(keep=id y1-y5);
if gender=2;
proc print;
run;

猜你喜欢

转载自blog.csdn.net/m0_52739647/article/details/120750196