SAS EG lagcalculation issue, not calculating las as t - t-1 -
can 1 resolve issue there:
data want; set have; mac; if first.mac do; daydif=0; kmdif=0; end; else do; daydif = date - lag(date); /* calculate difference between 2 dates */ kmdiff = kms - lag(kms); end; run;
and got result (0 in first line . in second):
mac date kms daydif kmdif sp0001 10dec07 1885462.00000 0 0 sp0001 12dec07 1885462.00000 . . sp0001 30apr09 1885462.00000 505 0 sp0001 15jul09 1886577.00000 76 1115 sp0001 16jul09 1887667.00000 1 1090 sp0001 17jul09 1889181.00000 1 1514 sp0001 17jul09 1888825.00000 0 -356 . .
(here when machine changed, lag taken t - (t-2) , not t - (t-1) ) why???? wrong in code ??
machine date kms daydif kmdif sp0001 01oct14 2898108.00000 1 1059 sp0001 02oct14 2899148.00000 1 1040 hp0001 03oct14 2900334.00000 1 1186 hp0002 17jan08 926384.00000 0 0 hp0002 18jan08 926384.00000 -2450 -1973950 hp0002 28apr09 1237332.00000 466 310948 hp0002 29apr09 1238599.00000 1 1267
the values lag()
function not taken previous observation (a common misconception).. they stored in memory every time function executed (see documentation).
in example, when machine changes, lag function not executed due conditional logic (if first.mac / else
) - "t-2" value result previous iteration. try following:
data want; set have; mac; if first.mac do; daydif=lag(date); /* executing lag subsequent iteration */ daydif=0; kmdif=0; end; else do; daydif = date - lag(date); /* calculate difference between 2 dates */ kmdiff = kms - lag(kms); end; run;
Comments
Post a Comment