两组产品 SAS

Product by two groups SAS

我正在尝试按两组创建产品:id1id2

数据集如下所示:

data test;
    input id1 id2 value;
    datalines;

1 199001 1.762681948
1 199001 1.775245162
1 199001 1.428673376
1 199002 1.175974146
1 199002 1.236166022
1 199002 1.608842974
1 199003 1.673956674
1 199003 1.05879051
1 199003 1.565500916
2 199002 1.838999925
2 199002 .
2 199002 1.984415322
2 199003 1.096820927
2 199003 1.734215557
2 199003 1.157566337
;
run;

我想根据第一列和第二列创建最后一列 value 的产品。 IE。组 id1=1id2=199001 的输出应为:1.7626x1.7775x1.429=4.47。即输出应如下所示:

1   199001  4.47059416
1   199002  2.338773875
1   199003  2.774645982
2   199002  .
2   199003  2.201834613

这是 SAS 最佳三连胜的完美示例:first./last.retain 和分组处理。

data want;
    set test;
    by id1 id2;
    retain product;

    if(first.id2) then product = value;
        else product = product * value;

    if(last.id2) then output;
run;

如果您使用值的 LOG(),您可以使用乘法转换为加法的事实。然后你可以使用 SQL.

的 SUM() 聚合函数
proc sql ;
create table want as
  select id1,id2,exp(sum(log(value))) as product
  from have
  group by 1,2
;
quit;

如果我们要求存在缺失值到 return 缺失值,则添加 CASE 语句。您可能还想添加逻辑来处理零。

create table want as
  select id1,id2
       , case
           when (sum(value=0)) then 0
           when (sum(missing(value))) then .
           else exp(sum(log(case when (value) then value else 1 end)))
         end as product
  from have
  group by 1,2
;

内部 CASE 将消除有关尝试获取零值或缺失值的 LOG() 的注释。

该代码使用 SAS 布尔逻辑为真生成 1,为假生成零,并将零值或缺失值评估为假,将任何其他值视为真。