sas - 变量数量的平均值,其中变量数量由单独的列指定

标签 sas

我想创建一个新列,其值等于其他列中值的平均值。但我要取平均值的列数是由变量决定的。我的数据如下所示,“长度”指示我想要平均的 x1-x5 列数:

data have;
    input ID $ length x1 x2 x3 x4 x5;
    datalines;
A 5 8 234 79 36 78
B 4 8 26 589 3 54
C 3 19 892 764 89 43
D 5 72 48 65 4 9
;
run;

我想得到下面的结果,其中“avg”是指定列的平均值。

data want;
    input ID $ length avg
    datalines;
A 5 87
B 4 156.5
C 3 558.3
D 5 39.6
;
run;

有什么建议吗?谢谢!抱歉,这个糟糕的标题,我已经尽力了。

最佳答案

您必须做更多的工作,因为 mean(of x[1]-x[length]) 不是有效的语法。相反,将值保存到临时数组并取其平均值,然后在每一行重置它。例如:

tmp1 tmp2 tmp3 tmp4 tmp5
8    234  79   36   78
8    26   589  3    .
19   892  764  .    . 
72   48   65   4    9

data want;
    set have;
    array x[*] x:;
    array tmp[5] _temporary_;
    
    /* Reset the temp array */
    call missing(of tmp[*]);

    /* Save each value of x to the temp array */
    do i = 1 to length;
        tmp[i] = x[i];
    end;

    /* Get the average of the non-missing values in the temp array */
    avg = mean(of tmp[*]);

    drop i;
run;

关于sas - 变量数量的平均值,其中变量数量由单独的列指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73705814/

相关文章:

python - 使用 python 合并具有重复行的数据

sas - 如何在SAS数据集中查找两个变量并更新值

sql - 使用内联接更新 SAS PROC SQL

sas - 在SAS中单独解析标题行

sql - SAS - 创建增量表

SAS 警告 : CREATE TABLE statement recursively references the target table

sas - 仅查找名字中的连字符

c++ - 什么会导致像这样的 'doubled'堆栈?

time - 格式化 HH :MM column when reading data into SAS

hadoop - 将SAS数据集加载到Hadoop中