如何在if语句中创建数组
Posted
技术标签:
【中文标题】如何在if语句中创建数组【英文标题】:How to create array in if statement 【发布时间】:2022-01-14 23:57:13 【问题描述】:我想复制和修改表中的特定行。
之前:
xyz_id | letter | Col_1 | ...|
1 | Z | V1 | ... |
2 | Z | V2 | ... |
3 | Z | V3 | ... |
之后:
xyz_id | letter | Col_1 | ...|
1 | A | V1.1 | ... |
1 | B | V1.2 | ... |
1 | C | V1.3 | ... |
2 | A | V2.1 | ... |
2 | B | V2.2 | ... |
2 | C | V2.3 | ... |
3 | A | V3.1 | ... |
3 | B | V3.2 | ... |
3 | C | V3.3 | ... |
我已经准备了以下代码:
data test2;
set test;
array letters 3 $3 _temporary_ ('A', 'B', 'C');
array weights 3 _temporary_ (1,2,3);
/* if xyz_id = '1' */
/* then array weights 3 _temporary_ (1,2,3);*/
/* else if xyz_id = '2'*/
/* then array weights 3 _temporary_ (8,7,6);*/
/* else array weights 3 _temporary_ (1,1,1)*/
do i = 1 to 8;
letter = letters(i);
Col_A = Col_A * weights(i);
output;
end;
drop i;
run;
现在,我正在尝试使 weights 依赖于 letter 列(注释代码) - 但没有任何成功。我也试过了:
array weights_1 3 _temporary_ (1,2,3);
if xyz_id = '1'
then weights = weights_1;
但效果不佳。
有什么建议吗?
【问题讨论】:
【参考方案1】:需要添加一个 3D 数组。
array weights3,3
c1_w1-c1_w8
c2_w1-c2_w8
c3_w1-c3_w8
(
0.1 0.1 /*letter 1*/
1 22 23 /*letter 2*/
1 32 33 /*letter 3*/
);
所以最后的代码是:
data test2;
set test;
array letters 3 $3 _temporary_ ('A', 'B', 'C');
array weights 3 _temporary_ (1,2,3);
if xyz_id = '1'
then weights_dim=1;
else if xyz_id = '2'
then weights_dim=2;
else if xyz_id = '3'
then weights_dim=3;
weight = weightsweights_dim, i;
do i = 1 to 8;
letter = letters(i);
Col_A = Col_A * weight;
output;
end;
drop i;
run;
【讨论】:
【参考方案2】:怎么样
data have;
input xyz_id letter $ Col_1 $;
datalines;
1 Z V1
2 Z V2
3 Z V3
;
data want;
set have;
array letters 3 $3 _temporary_ ('A', 'B', 'C');
array weights 3 _temporary_ (1,2,3);
c = Col_1;
do i = 1 to 3;
letter = letters[i];
Col_1 = catx('.', c, weights[i]);
output;
end;
drop i c;
run;
【讨论】:
以上是关于如何在if语句中创建数组的主要内容,如果未能解决你的问题,请参考以下文章