gpt4 book ai didi

SAS 哈希对象总和

转载 作者:行者123 更新时间:2023-12-04 21:40:05 27 4
gpt4 key购买 nike

我想了解 SAS 哈希对象的 sum() 函数。据我了解,suminc: 定义变量SAS 哈希对象跟踪,而 sum() 将对该变量的值求和。

假设我有数据集

data sample;
input id x;
datalines;
1 350
1 220
1 300
2 300
2 500
;
run;

我希望聚合是

id x_sum
2 800
1 870

但是,我的哈希码:

data _null_;
set sample end= done;

length x_sum 8;

if _N_ = 1 then
do;
declare hash T(suminc:"x");
T.definekey("id");
T.definedata("id");
T.definedata("x_sum");
T.definedone();
end;


T.ref();

T.sum(sum:x_sum);

put _all_;


T.replace();

if done then T.output(dataset: "my_set");

run;

输出:

id x_sum
2 800
1 520

作为数据集和日志:

done=0 id=1 x=350 x_sum=350 _ERROR_=0 _N_=1
done=0 id=1 x=220 x_sum=570 _ERROR_=0 _N_=2
**done=0 id=1 x=300 x_sum=520 _ERROR_=0 _N_=3**
done=0 id=2 x=300 x_sum=300 _ERROR_=0 _N_=4
done=1 id=2 x=500 x_sum=800 _ERROR_=0 _N_=5

谁能给我解释一下这是怎么回事?

所有评论后更新:

大家好,我是 Stack Overflow 的新手,所以我仍在研究这个“勾选答案”系统……我觉得每个人都做出了贡献。

不管怎样,经过大量的实验,我弄明白了是怎么回事——

基本上,每当 .sum() .replace() 被调用时,求和计数器都会重置为零。 这, 并不是真正的 replace()等等 ,这就是结果为何如此的原因 - sum() 重置了我的计数,因此 ref() 只是对前 2 个观察结果求和。

希望这对大家有用。如果其他人有任何见解,请分享。

最佳答案

问题是您对 Replace() 的使用。来自文档(9.3 语言引用概念,使用散列对象):

This SUMINC tag instructs the hash object to allocate internal storage for maintaining a summary value for each key. The summary value of a hash key is initialized to the value of the SUMINC variable whenever the ADD or REPLACE method is used. The summary value of a hash key is incremented by the value of the SUMINC variable whenever the FIND, CHECK, or REF method is used.

我认为重要的一点是“汇总值”不是DATA步变量x_sum,也不是作为数据变量存储在哈希表中的x_sum。它存储在哈希表的定义数据之外。辅助信息实际上是 key 的一个属性。 (在我脑海里……)

如果您注释掉 replace(),您的代码可以工作(您在 PDV 中获得正确的 x_sum 值),但问题是 x_sum 永远不会写入哈希表。因此,您调用 replace() 将 x_sum 写入哈希表,导致汇总值被初始化为 x 值的不幸副作用。我认为解决方法是在调用 replace() 之前分配 x=x_sum。这样当 replace() 将汇总值重新初始化为 x 的值时,x 保存当前汇总值。我很难用语言表达,但看到下面只添加了一个声明。

data _null_;
set sample end= done;

length x_sum 8;

if _N_ = 1 then
do;
declare hash T(suminc:"x");
T.definekey("id");
T.definedata("id");
T.definedata("x_sum");
T.definedone();
end;
T.ref();
T.sum(sum:x_sum);
put _all_;

x=x_sum; *Replace method will initialize the summary value to x! ;

T.replace();
if done then T.output(dataset: "my_set");
run;

关于SAS 哈希对象总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30293213/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com