Help using Base SAS procedures

do loop with LAG function

Accepted Solution Solved
Reply
Contributor
Posts: 56
Accepted Solution

do loop with LAG function

Hi, I want to use a LAG function in a 'do' loop but the code does not work, any ideas why?

data test_data;

   input X;

   datalines;

     0.2

     0.1

    -0.3

     0.1

     0.1

    -0.1

     0.2

;

run;

data autocorrelation;

  set test_data;

  do n=1 to 3

  r&n = (X - 0.0429)*(lag&n(X) - 0.0429) ;

run;

Also, the numeric value 0.0429 used is the mean of 'X', but mean(X) does not work, so how can I code in the mean value of X and not have to hard code is numeric value.


Accepted Solutions
Solution
‎04-30-2012 07:49 AM
Respected Advisor
Posts: 3,156

Re: do loop with LAG function

Hi,

1. you have to preassign macro variable to use it in data step, as macro variable resolves way before data step being executed. Or you need to include the whole thing into a macro.

2. Mean() does not work that way in data step. you can use proc sql or proc freq or proc mean to get it before you processing with your data step.

3. BTW, you missed one semicolon.

the following does what you want (hopefully):

data test_data;

  input X;

  datalines;

  0.2

  0.1

  -0.3

  0.1

  0.1

  -0.1

  0.2

;

run;

proc sql;

select mean(x) into :mx from test_data;

quit;

%macro test;

data autocorrelation;

  set test_data;

  %do n=1 %to 3;

  r&n = (X - &mx)*(lag&n(X) - &mx) ;

  %end;

run;

%mend;

%test

Regards,

Haikuo

View solution in original post


All Replies
Solution
‎04-30-2012 07:49 AM
Respected Advisor
Posts: 3,156

Re: do loop with LAG function

Hi,

1. you have to preassign macro variable to use it in data step, as macro variable resolves way before data step being executed. Or you need to include the whole thing into a macro.

2. Mean() does not work that way in data step. you can use proc sql or proc freq or proc mean to get it before you processing with your data step.

3. BTW, you missed one semicolon.

the following does what you want (hopefully):

data test_data;

  input X;

  datalines;

  0.2

  0.1

  -0.3

  0.1

  0.1

  -0.1

  0.2

;

run;

proc sql;

select mean(x) into :mx from test_data;

quit;

%macro test;

data autocorrelation;

  set test_data;

  %do n=1 %to 3;

  r&n = (X - &mx)*(lag&n(X) - &mx) ;

  %end;

run;

%mend;

%test

Regards,

Haikuo

Contributor
Posts: 56

Re: do loop with LAG function

thanks that's really useful, it gives me some insight into how to code in SAS, really useful answer, thanks

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 2 replies
  • 3440 views
  • 1 like
  • 2 in conversation