Creating Interdependent Data in SAS

I am trying to compute a column in SAS that has a dependency on itself. For example, I have the following list of initial values

ID Var_X Var_Y Var_Z 1 2 3 . 2 . 2 . 3 . . . 4 . . . 5 . . . 6 . . . 7 . . . 

I need to fill in the blanks. The formulas are as follows:

  Var_Z = 0.1 + 4*Var_x + 5*Var_Y Var_X = lag1(Var_Z) Var_Y = lag2(Var_Z) 

As we can see, the values โ€‹โ€‹of Var_X, Var_Y and Var_Z are interdependent. Thus, the calculation must follow a certain order.

 First we compute when ID = 1, Var_Z = 0.1 + 4*2 + 5*3 = 23.1 Next, when ID = 2, Var_X = lag1(Var_Z) = 23.1 

Var_Y does not need to be calculated with ID = 2, since here we already have the initial value. So we have

  ID Var_X Var_Y Var_Z 1 2 3 23.1 2 23.1 2 102.5 (= 0.1 + 4*23.1 +5*2) 3 . . . 4 . . . 5 . . . 6 . . . 7 . . . 

We continue to repeat this procedure until all values โ€‹โ€‹are calculated.

Is there any way SAS can handle this? I tried the DO loop, but I think I didn't program it very well. It just stops after ID = 2.

I'm new to SAS, so I don't know if there is a way that SAS can handle this easily. They will be waiting for your suggestions.

+4
source share
2 answers

You do not need to use LAG or RETAIN if you just do it in one step of the data. The DO loop itself will be well understood. RETAIN is only needed if we are doing something using a pre-existing dataset, but there really is no reason to use it.

I use the shortcut here - while you describe VAR_Y in terms of VAR_Z, you really mean that after one iteration, VAR_Z goes into VAR_X and VAR_X goes into VAR_Y, so I do this (in the correct order so as not to mix things up) .

 data test_data; if _n_ = 1 then do; var_x=2; var_y=3; end; do _iter = 1 to 7; var_z = 0.1+4*var_x+5*var_y; output; var_y=var_x; var_x=var_z; end; run; proc print data=test_data; run; 
+5
source

I believe that you can do this in a DO loop - the key makes SAS remember the last values โ€‹โ€‹of your variables. My suggestion is to give a little push to a simple โ€œcountingโ€ program, which in pseudo-SAS code looks something like this:

 Do i = 1 to 100; i = i + 1; run; 

And look at what syntax is in SAS. I suspect your problem is that you are not using a save statement in your DO loop. Check the SAS documentation and see if it fixes your problem?

+2
source

Source: https://habr.com/ru/post/1433057/


All Articles