《SAS编程与数据挖掘商业案例》学习笔记之十三

来源:互联网 发布:淘宝差评后售后退款 编辑:程序博客网 时间:2024/04/29 09:34

本次重点:data步循环与控制

涉及:if/then/else语句,select语句,do语句,continue语句,leave语句

1.if then else 语句

高效率的if应用:

1

If  x=1 then y=1;

Else if x=2  then y=2;

Else y=3;

对于每一个数据集的观测,if-then-else只会判断一次,为真则执行

2

If status=1 then

If status=5 then

If status=9 then output;

高效率:包含一个序列if-then语句,只要其中有一个if为假,则程序将不再执行下面的if语句

If status=1 and status=5 andstatus=9 then output;则无效率,需要判断所有的条件

3

If status in (1,5,8,9) then newstat="single";

Else  newstat='not single'

高效率:对于在in算符里面的表达式,只要有一个为真,则sas就执行后面的语句

如果用or语句的形式,则需要判断所有的条件是否为真,效率则低

2.select语句

libname chapt6 'f:\data_model\book_data\chapt6';

data fishdata4;

    set chapt6.fishlength(keep=location date _name_ measurement);

    by location date;

array tr[1:4] length1-length4;

    retain length1-length4;

    if first.date then do i=1 to 4;

        tr(i)=0;

    end;

    select(_name_);

      when ('length1') length1=measurement;

      when ('length2') length2=measurement;

      when ('length3') length3=measurement;

      when ('length4') length4=measurement;

      otherwise;

    end;

if last.date;

keep location date length1-length4;

run;

拉直数据,相当于行转列;

 

中间黄色部分也可以用select的另一种方式:

    select;

      when (_name_='length1') length1=measurement;

      when (_name_='length2') length2=measurement;

      when (_name_='length3') length3=measurement;

      when (_name_='length4') length4=measurement;

      otherwise;

    end;

3.do语句

1 do组语句

Do;

 执行程序块;

end

常用于和if then/else语句中

2do循环语句

Do   i=1 to 10;

Do  i=1 to exit;

Do i=1 to n-1;

Do i=1 to 100 by 10; --规定步长

Do i=1 to 20 by 2 until (x>y);   --每次循环后被计算

Do i=10 to 0 by -1 while(month='JAN');  --每次循环前计算

3do while语句  循环前判断条件

n=0;

Do while (n<5);

Put n=;

n 1;

End;

4)do until 语句  在循环后计算,故循环至少被执行一次

n=0;

Do until(n>=5);

Put n=;

n 1;

End;

商业实战;

libname ch7 'f:\data_model\book_data\chapt7';

proc sort data=ch7.smooth;by cid month;run;

data smooth;

set ch7.smooth;

by cid;

array lags(12);

lags(1)=lag(balance);

do i=2 to 12;

    lags(i)=lag(lags(i-1));

    end;

do j=12 to 2 by -1;

if j gt cns then lags(j)=.;

put j=;

end;

if first.cid then do

       cns=0;

       do i=1 to 12;lags(i)=.;

       end;

    end;

cns 1;

mean6=mean(of lags1-lags6);

mean12=mean(of lags1 - lags12);

 

run;

计算每个客户在每个月前6个月和前12个月移动平均余额;

4.控制语句

continue语句和leave语句

data a;

do i=1 to 20;

sumx i;

if sumx le 15 then continue;

output;

end;run;

sumx<15时跳出本次循环,因而最后返回的是最后的15条数据

data a;

do i=1 to 10;

sumx i;

if sumx gt 15 then leave;

output;

end;

run;

sumx大于15时,结束循环,故只输出前5条数据

注:

continue停止当前循环继续下一次循环;

leave跳出当前循环,执行下一个sas语句;

continue值能在do循环中;

leave语句可以同do循环活select语句共同使用。

0 0
原创粉丝点击