条件格式化新变量

huangapple go评论75阅读模式
英文:

Conditional formatting of a new variable

问题

我有以下数据集:

    Test1    Test2     Test3      Test4    
      0        0         0          0        
      0        0         0          0
      1        0         1          0
      0        0         0          0
      0        1         0          1

是否有一种方法可以创建一个新变量,当所有变量Test中都为"0"时,新变量将包含索引"2"?如果至少有一个变量Test中包含"1",则New_Var中的索引应为"0"。
谢谢你提前。

期望的输出:

    Test1    Test2     Test3      Test4    New_Var 
      0        0         0          0         2     
      0        0         0          0         2
      1        0         1          0         0
      0        0         0          0         2
      0        1         0          1         0
英文:

I have the following dataset:
> Test1 Test2 Test3 Test4
> 0 0 0 0
> 0 0 0 0
> 1 0 1 0
> 0 0 0 0
> 0 1 0 1

Is there a way to create a new variable that will contain index "2" when "0" is in all variables Test* ? If there is "1" in at least one of the variables Test* the index in New_Var should be 0.
Thank you in advance.

Desired output:

> Test1 Test2 Test3 Test4 New_Var
> 0 0 0 0 2
> 0 0 0 0 2
> 1 0 1 0 0
> 0 0 0 0 2
> 0 1 0 1 0

答案1

得分: 4

你可以通过对test1-test4中的所有变量求和来有条件地检查这个条件。由于它们以这种方式命名,你可以使用sum(of var1-varn)的快捷方式。如果你使用sum(of test1-test4),SAS会自动将其转换为sum(test1, test2, test3, test4)。这也适用于数组。例如,sum(of arr[*])将对数组arr中的所有变量求和。

data want;
    set have;

    if(sum(of test1-test4) = 0) then New_Var = 2;
    else New_Var = 0;
run;
Test1	Test2	Test3	Test4	New_Var
0	    0	    0	    0	    2
0	    0	    0	    0	    2
1	    0	    1	    0	    0
0	    0	    0	    0	    2
0	    1	    0	    1	    0

请注意,以上是提供的代码和示例输出。

英文:

You can check for this conditionally by summing all the variables in test1-test4. Since they're named this way, you can use the sum(of var1-varn) shortcut. If you use sum(of test1-test4), SAS automatically translates this to sum(test1, test2, test3, test4). This also works for arrays as well. For example, sum(of arr[*]) will sum all the variables in the array arr.

data want;
    set have;

    if(sum(of test1-test4) = 0) then New_Var = 2;
        else New_Var = 0;
run;
Test1	Test2	Test3	Test4	New_Var
0	    0	    0	    0	    2
0	    0	    0	    0	    2
1	    0	    1	    0	    0
0	    0	    0	    0	    2
0	    1	    0	    1	    0

huangapple
  • 本文由 发表于 2023年8月9日 18:17:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76866781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定