全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 SAS专版
8000 9
2014-04-11
我现在有如下的表格

data have;
input id $ num;
datalines;
a 1
a 2
a 4
a 3
b 2
b 3
b 9
;
run;

每个id的数据都是按日期排好序的,为方便就不列日期了。我要得到的是每个id,自初始第一个观测开始至当前观测的平均值和标准差,即得到如下的结果:

id   num   mean                              std
a    1          1                               #DIV/0!
a    2          1.5                            0.707106781
a    4          2.333333333            1.527525232
a    3          2.5                            1.290994449
b    2          2                              #DIV/0!
b    3          2.5                           0.707106781
b    9          4.666666667           3.785938897

首先,我想过用array来做,但是因为这里的需要计算的数会逐渐增加,而且我的表格的观测数量很大,用array可能会比较耗时间。

另外,好像也不能用retain来做。只求平均值的话,用retain计算累积值再平均还比较方便,但是求标准差的话,估计就麻烦了。

现在想来用R的话会很方便,但是还是想用SAS实现下。现在想得头都大了,所以请教版上高人了,多谢!
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2014-4-11 19:31:50
关于标准差计算可使用简化公式。


复制代码


2014-04-12_000314.gif
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2014-4-11 23:03:28
Using PROC SQL for calculating Moving average, std

复制代码



SQL_moving.JPG
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2014-4-12 10:36:16
There are a couple of ways.

One is to use a recursive formula. Here is wikipedia link

http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance

The other is to use SAS function. Either way one pass is enough.

data have;
input id $ num;
datalines;
a 1
a 2
a 4
a 3
b 2
b 3
b 9
;


data need;
  set have;
  by id;
  array tmp[10000] _temporary_;
  if first.id then n=0 ;
  n+1;
  tmp[n]=num;
  mean=mean(of tmp(*));
  std =std(of tmp(*));
  if last.id then do;
     do i=1 to n;
       tmp=.;
     end;
  end;
  drop n i;
  run;

  proc print;run;
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2014-4-12 10:44:26
bobguy 发表于 2014-4-12 10:36
There are a couple of ways.

One is to use a recursive formula. Here is wikipedia link
Here is a more concise solution.

data need;
  set have;
  by id;
  array tmp[10000] _temporary_;
  if first.id then n=0 ;
  n+1;
  tmp[n]=num;
  mean=mean(of tmp(*));
  std =std(of tmp(*));
  if last.id then call missing (of tmp(*));
  drop n ;
  run;

  proc print;run;
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2014-4-14 13:26:54
zhengbo8 发表于 2014-4-11 19:31
关于标准差计算可使用简化公式。
多谢

用这个公式就没我之前的问题了,当时对着$\sum{(x_i-\bar{x})^2}$看了半天,竟然忘了还有这公式了
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

点击查看更多内容…
相关推荐
栏目导航
热门文章
推荐文章

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群