sas是个很强大的软件,我从接触到现在有4年时间了,期间间断的在学习中用到,本人不是专业统计人士,只是需要的时候用到,临时研究研究,所以本人水平一直不稳定 。好,闲话不多说了,回归正题。
在科研资料处理中我经常会遇到问卷中多选题的问题,如下面这个数据集:
data a;
input id x ;
cards;
1 123
2 234
3 134
4 14
5 24
6 45
7 12
8 135
9 1
;
run;
变量X是问卷中的多选题,有5个选项,录入时图方便,选择ABC,就录入成123……,现在想对其进行处理,就必需将其二分类化,最早的时候我是这样做的:
data a_new;
set a;
x1=index(x,'1'); /*INDEX(s,s1) 查找s1在s中出现的位置。找不到时返回0。*/
x2=index(x,'2'); /*引号不可少*/
x3=index(x,'3');
x4=index(x,'4');
x5=index(x,'5');
run;
data a_new1;
set a_new;
if x1^=0 then x1=1;
if x2^=0 then x2=1;
if x3^=0 then x3=1;
if x4^=0 then x4=1;
if x5^=0 then x5=1;
run;
后来随着我sas水平的提高,将程序进行了精简:
data a_new;
set a;
if index(x,'1')^=0 then x1=1; else x1=0;
if index(x,'2')^=0 then x2=1; else x2=0;
if index(x,'3')^=0 then x3=1; else x3=0;
if index(x,'4')^=0 then x4=1; else x4=0;
if index(x,'5')^=0 then x5=1; else x5=0;
run;
再后来,我接触了sas的宏编程技术,就有了把处理过程编程一个宏程序的想法,这样可以改个参数,直接调用即可,现将程序分享如下:
%let data=a; /*数据集名称*/
%let v=x; /*变量名*/
%let m=5; /*多选项数*/
%macro dx;
data &data._new;
set &data;
%do i=1 %to &m;
if index(&v,"&i")^=0 then &v&i=1;else &v&i=0; /*一定要用双引号*/
%end;
run;
%mend;
%dx;
上面这段程序,只要改变“%let” 部分三个参数,全选运行就可以达到分变量的效果。
最后,将上述sas程序提供给大家下载,欢迎sas高手们指教,看能不能有更好的方法,或者再精简程序。