使用 SAS 对多列求和 [英] Summing Multiple Columns using SAS

查看:255
本文介绍了使用 SAS 对多列求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 SAS 添加多列.

I want to add multiple columns using SAS.

数据有:

D C1 C2 C3 C4 C5.....   
J 01 02 00 04 15 
F 05 00 09 11 00  
M 12 14 88 00 00
A 55 03 00 00 00  
M 67 00 00 00 00

我不想这样做

数据需求;

Set Have;  
N1 = C1;  
N2 = C1+C2;  
N3 = C1+C2+C3;  
N4 = C1+C2+C3+C4; 
N5 = C1+C2+C3+C4+C5;
Keep N:    
Run; 

希望我的桌子看起来像这样.

want my table to look like this.

数据表想要

D N1  N2  N3  N4  N5.....   
J 01  03  03  07  22 
F 05  05  14  25  00  
M 12  26  114 00  00
A 55  58  00  00  00  
M 67  00  00  00  00

请注意,我将有很多列,并且数量会有所不同.我需要一个动态代码,它会自动计算列数并执行计算.我需要底部三角形保持 0 而不是继续加起来.如果像示例中的 (J,C3) 那样存在零值,它仍然需要执行.我也需要它来保持订单.无法更改数据顺序.

Note that I will have a lot of columns and the number will vary. I need a dynamic code which will automatically count the number of columns and perform the calculation. I need the bottom triangle to stay 0 and not keep adding it up. It still need to perform if there is zero value like in the case of (J,C3) in the example. I also need it to keep the order. Cannot change the order of the data.

推荐答案

你可以用数组来做到这一点.

You can do this with arrays.

首先生成一些假数据.这有 100 个变量和 100 个观察结果.

First generate some fake data. This has 100 variables and 100 observarions.

data have;
array C[100];
do i=1 to 100;
    do j=1 to 100;
        c[j] = j;
    end;
    output;
end;
drop i j;
run;

现在,获取数值变量的计数:

Now, get a count of the numeric variables:

data _null_;
set have;
array x[*] _numeric_;
call symput("nVar",dim(x));
stop;
run;

%put Number Variables = &nVar;

这告诉我 Number Variables = 100 -- 一切都很好.

This tells me Number Variables = 100 -- all good.

现在使用数据步骤进行求和.

Now use a Data Step to do your sums.

data want;
set have nobs=nobs;
array x[&nVar] _numeric_;
array N[&nVar];

do i=1 to &nVar;
    do j=1 to i;
        if j <= (nobs - _n_ + 1) then
           N[i] = sum(N[i],x[j]);
        else 
           N[i] = 0; /*Change to missing (.) if needed*/
    end;
end;

keep N:;
run;

这篇关于使用 SAS 对多列求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆