heyydrien
heyydrien

Reputation: 981

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

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.

Upvotes: 0

Views: 249

Answers (1)

Tom
Tom

Reputation: 51621

It is easy enough to do with the LAG() function. Just remember to make sure to always run the LAG() function on every observation. So first calculate VAR2 and then if it is the first observation then overwrite the value with your required initial value.

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
;

Upvotes: 1

Related Questions