Create new variable based on column value in current row as well as previous row?

时间:2017-07-17 15:30:54

标签: sas

Given the data set:

Year   var1
0      .56
1      .39
2      .28
3      .15
4      .09

How would you create a new column, var2 = (var1n)/(var1n-1), and have var21 equal to var11? The desired output would look like this:

Year   var1   var2
0      .56    .56
1      .39    .70
2      .28    .72
3      .15    .54
4      .09    .60

I know how to use the RETAIN statement for creating a cumulative variable but I'm not sure how to use it for this particular task. Any insight you might have is greatly appreciated.

1 个答案:

答案 0 :(得分:1)

使用LAG()函数很容易。请记住确保始终在每次观察时运行LAG()函数。因此,首先计算VAR2,然后如果它是第一个观测值,则用您所需的初始值覆盖该值。

data want ;
  input year var1 ;
  var2 = divide(var1,lag(var1));
  if _n_=1 then var2=var1;
cards;
0      .56
1      .39
2      .28
3      .15
4      .09
;