【问题标题】:If-else then do in SASIf-else 然后在 SAS 中执行
【发布时间】:2020-09-02 17:14:49
【问题描述】:

您好,我想知道多重 if then 条件的步骤。

我想做以下事情:

data _ ;
set _ ;
if condition 1 is true then do; 
if sub condition 1 is true then _ ;
else if sub condition2 is true then _;
else if ... ;
end;
else if condition 2 is true then do; /* Is it right? */
if sub condition 1 is true then _ ;
else if sub condition2 is true then _;
else if ... ;
end;
run;

你能告诉我正确的步骤是什么吗?我应该包括 else if 还是 else do?

例如:条件 1 可以取值 1 或 0。子条件(我将它们称为 test1、test2、test3、...)是其他条件。所以我会有类似的东西:

data _ ;
set _ ;
if condition1 = 1 then do;
if test1 = . then test3=test2; else test3=test1; 
else if test1 = 'My test' or test2= 'My test' then test3=test2 else test3=test2; 
end; 
else if condition1=0 then do;
if test1 = . then test3=test2; else test3=test1; 
else if test1 = 'My test' or test2= 'My test' then test3=test2 else test3=test2; 
end; 
else test3=test2;
run; 

数据样本可以是:

condition1   test1        test2
1             .            M
0             My test      .
1             Love        home
0             Home         .

我想选择的是,基于 condition1 值,

如果 condition1 是 1 并且 test1 是 .然后赋值给 test3 test2 的值,否则 test3=test1;等等。

我的预期输出是:

condition1   test1        test2       test3
1             .            M           M
0             My test      .           My test
1             Love        home         Love
0             Home         .           Home

【问题讨论】:

  • 不确定我是否理解问题所在。 DO/END 块只是为了让您可以用多个语句替换单个语句。
  • 在您的示例中,变量 TEST1 是数字还是字符?在某些地方,您将其视为数字,test1 = .,而在其他地方,您将其视为字符,test1 = 'My test'。您可以使用missing() 函数来测试变量是否丢失,它对数字或字符变量的工作方式相同,此外它还会检测特殊的缺失值,例如.A.Z 等。
  • 在我找到的数据集中。和 NA 值(后者作为字符串)。有没有办法检查变量的类型?
  • PROC CONTENTS 将显示有关数据集的信息。

标签: sas


【解决方案1】:

不确定你在问什么,但也许这会对你有所帮助。

您可以将嵌套的 if 视为附加条件。所以如果你有

if test1 then do;
  if test2 then statement1 ;
  else if test3 then statement2 ;
end;

你可以改写成

if test1 and test2 then statement1 ;
else if test1 and test3 then statement2 ;

【讨论】:

  • 谢谢汤姆。那么同样的方法会很好用 then 吗?有两种不同的条件(例如条件 1 = 1,条件 2 是条件 1 的另一个值,如果是二进制,即 0)。然后我考虑子条件(你的 test2 和 test3)。问题是逻辑。我没有数据集,但如果你喜欢的话,我可能会想到一些可以作为例子的东西
  • 我在我的问题中包含了一个可能的例子。感谢您的帮助
  • 要查看这两种方法是否相同,请考虑测试条件的每个可能值。因此,如果您有两个测试,则有 4 种可能的组合,FF、FT、TF 和 TT。考虑每个并检查两个程序是否产生相同的结果。对于 N 次测试,有 2**N 种可能的组合。
  • 谢谢汤姆。我会检查并告诉你
猜你喜欢
  • 2019-05-16
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-18
相关资源
最近更新 更多