BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
skipper
Calcite | Level 5

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.

1 ACCEPTED SOLUTION

Accepted Solutions
Haikuo
Onyx | Level 15

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

2 REPLIES 2
Haikuo
Onyx | Level 15

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

skipper
Calcite | Level 5

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

SAS Innovate 2025: Save the Date

 SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!

Save the date!

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

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