lag函数

    技术2022-05-19  29

    今天看了这么篇文章《LAG - the Very Powerful and Easily Misused SAS® Function》——

    Yunchao (Susan) Tian, Social & Scientific Systems, Inc., Silver Spring, MD

    该文中详细介绍解读了LAG函数的运用并附有很不错的例子予以说明。这里以鄙人弱弱的英语和sas理解能力,再次复述一下几个例子。

    例一,已知数据是2001-2005年间二手房的中介价格,要求计算每年增加的价格:

    data example1;    input year $ price;    length price;    cards; 2001 200000 2002 220000 2003 250000 2004 280000 2005 310000 ; run; data example1_right;    set example1;    lag_price=lag(price);    dif_price=price-lag_lag_price;    per_increase=(dif_price-lag_price)*100; /*per_increase=(dif(price)/lag(price))*100*/ run;

    例二、依据前一年的价格对以后年度(缺失)的价格予以处理。这个例子中,缺失的值比前一年增加10%,比两年前则增加20%。

    data example3;    input county 1-4 year $ 6-9 price;    cards; 1001 2001 200000 1001 2002      . 1001 2003      . 1001 2004 280000 1001 2005 310000 1002 2001      . 1002 2002 240000 1002 2003 270000 1002 2004 300000 1002 2005 340000 1003 2001 280000 1003 2002 300000 1003 2003 330000 1003 2004 370000 1003 2005      . ; run; data example3_right; set example3;    lag_price=lag(price);    lag2_price=lag2(price);    lag_county=lag(county);    lag2_county=lag2(county);    if price ne . then price_impute=price;    else if price = . and county=lag_county and lag_price ne .        then price_impute=lag_price*1.1;    else if price = . and lag_price = . and county = lag2_county        and lag2_price ne . then price_impute = lag2_price*1.2; run;

     

     这里需要注意的是,使用lag函数时,要首先对变量使用lag函数,然后再进行其他有条件的运算。


    最新回复(0)