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
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.