首页 > 解决方案 > 将所有数组值设置为单个值

问题描述

如果满足某种条件,我想将数组中的所有值设置为 1,如果不满足条件,则执行计算。我目前正在使用一个非常慢的do循环。

我想知道是否有更快的方法。

data test2;
set test1;
array blah_{*} blah1-blah100;
array a_{*} a1-a100;
array b_{*} b1-b100;

do i=1 to 100;
blah_{i}=a_{i}/b_{i};
if b1=0 then blah_{i}=1;
end;

run;

我觉得 if 语句效率低下,因为我一次设置值 1 个单元格。有没有更好的办法?

标签: sas

解决方案


已经有几个很好的答案,但为了完整起见,这是一种非常愚蠢和危险的方法,可以在不使用循环的情况下一次更改所有数组值:

data test2;
set test1;
array blah_{*} blah1-blah100 (100*1);
array a_{*} a1-a100;
array b_{*} b1-b100;

/*Make a character copy of what an array of 100 1s looks like*/
length temp $800; *Allow 8 bytes per numeric variable;
retain temp;
if _n_ = 1 then temp = peekclong(addrlong(blah1), 800);

do i=1 to 100;
  blah_{i}=a_{i}/b_{i};
end;

/*Overwrite the array using the stored value from earlier*/
if b1=0 then call pokelong(temp,addrlong(blah1),800);

run;

推荐阅读