Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 利用SAS中的do循环计算移动平均_Loops_Sas - Fatal编程技术网

Loops 利用SAS中的do循环计算移动平均

Loops 利用SAS中的do循环计算移动平均,loops,sas,Loops,Sas,我试图找到一种使用SAS do循环计算移动平均线的方法。我有困难。我想计算一个4个单位的移动平均线 DATA data; INPUT a b; CARDS; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ; run; data test(drop = i); set data; retain c 0; do i = 1 to _n_-4; c = (c+a)/4; end; run; p

我试图找到一种使用SAS do循环计算移动平均线的方法。我有困难。我想计算一个4个单位的移动平均线

DATA data;
   INPUT a b;
   CARDS;
1 2
3 4 
5 6 
7 8 
9 10
11 12
13 14
15 16
17 18
;
run;    

data test(drop = i);
   set data;
   retain c 0;
   do i = 1 to _n_-4;
      c = (c+a)/4;
   end;
run;

proc print data = test;
run;

一种选择是使用“提前合并”:

DATA have;
 INPUT a b;
CARDS;
1 2
3 4 
5 6 
7 8 
9 10
11 12
13 14
15 16
17 18
;
run;

data want;
merge have have(firstobs=2 rename=a=a_1) have(firstobs=3 rename=a=a_2) have(firstobs=4 rename=a=a_3);
c = mean(of a:);
run;
每次合并的数据集向前移动一个数据集时,将数据合并到自身中-因此第二个数据集从2开始,第三个数据集从3开始,等等。这将在一行中提供所有4个“a”。

SAS有一个lag()函数。它所做的是创建应用它的变量的滞后。例如,如果您的数据如下所示:

DATA data;
 INPUT a ;
 CARDS;
1 
2 
3
4
5  
;
然后,下面将创建一个滞后1、2、3等变量

data data2; 
set data;
a_1=lag(a);
a_2=lag2(a);
a_3=lag3(a);
drop b;
run;
将创建以下数据集

a a_1 a_2 a_3
1 . . .
2 1 . .
3 2 1 .
4 3 2 1
等等。 移动平均线可以很容易地从这些数据中计算出来。 退房


(请注意,我没有机会运行这些代码,因此它们可能有错误。)

直接来自Cody的热门编程任务集以及如何处理它们

*Presenting a macro to compute a moving average;


%macro Moving_ave(In_dsn=,     /*Input data set name          */
                  Out_dsn=,    /*Output data set name         */
                  Var=,        /*Variable on which to compute
                                 the average                  */
                  Moving=,     /* Variable for moving average */
                  n=           /* Number of observations on which
                                  to compute the average      */);
   data &Out_dsn;
      set &In_dsn;
        ***compute the lags;
      _x1 = &Var;
      %do i = 1 %to &n - 1;
         %let Num = %eval(&i + 1);
          _x&Num = lag&i(&Var);
      %end;

        ***if the observation number is greater than or equal to the
           number of values needed for the moving average, output;
   if _n_ ge &n then do;
      &Moving = mean (of _x1 - _x&n);
      output;
   end;
   drop _x:;
   run;
%mend Moving_ave;


*Testing the macro;
%moving_Ave(In_dsn=data,
            Out_dsn=test,
            Var=a,
            Moving=Average,
            n=4)

首先检查您是否拥有SAS/ETS许可证,如果是,则PROC EXPAND具有计算移动平均数的功能