简体   繁体   中英

SAS cumulative return

I'm trying to get the cumulative product of variable x, giving P an initial value of 1. Using an iterative procedure I should get something simpler than datastep WANT below. Thanks.

DATA NUM;
INFILE DATALINES DSD;
INPUT X YEAR;
DATALINES;
0.99,2006
0.975,2007
0.983,2008
0.978,2009
;
DATA WANT;
set num;
by year;
lag_x=lag(x);
lag2_x=lag(lag_x);
lag3_x=lag(lag2_x);
if first.year then P=1; 
if year=2007 then P=lag_x;
if year=2008 then P=lag_x*lag2_x;
if year=2009 then P=lag_x*lag2_x*lag3_x;
run;

Use RETAIN instead of LAG.

data want2 ;
  set num ;
  retain p 1;
  put (year x p) (=);
  output;
  p=p*x;
run;

Results:

YEAR=2006 X=0.99 p=1
YEAR=2007 X=0.975 p=0.99
YEAR=2008 X=0.983 p=0.96525
YEAR=2009 X=0.978 p=0.94884075

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM