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.
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
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
thanks that's really useful, it gives me some insight into how to code in SAS, really useful answer, thanks
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.