首页 > 解决方案 > SAS:使用调用符号宏变量作为过滤标准

问题描述

我有一个具有字段 Income 、 Age 和 Cond 的数据,其中 A 和 B 是数字,而 Cond 包含条件(字符串),例如“If Income>=10000”、“If Age<=35”等。我想使用字段 Cond 进行过滤的数据。我正在使用 call symput 在数据步骤中创建运行时宏变量 bt 无法将其用作过滤标准。

data T2;
    set T1;
    CALL SYMPUT("Condition", Cond);
    &Condition.; /*this is the line which is not working*/
run;

标签: sas

解决方案


您正在混合范围。

一个正在运行的数据步骤不能改变它正在运行的源代码,所以你不能让一个数据步骤设置一个宏变量值,然后期望数据集使用宏变量的分辨率作为源代码。

您可以使用多种技术来评估表达式。

调用执行

您可以在 DATA 步运行时在宏环境中使用call EXECUTE表达式%EVAL。结果可以用SYMGET

想法的例子

  %let x = 0;

  data _null_;

    length expression $1000;

    expression = '%let x = %eval(10 + 20)';
    call execute (expression);

    x = symget('x');
    put x=;
  run;

使用这个想法

  data want;
    set have;

    condition = tranwrd(condition, 'age', cats(age));
    condition = tranwrd(condition, 'income', cats(income));

    call execute (cats('%let result = %eval(', condition, ')'));

    result = symget('result');

    * subsetting if based on dynamic evaluation of conditional expression;
    if result;
  run;

其他

执行动态代码的其他方法是通过函数RESOLVEDOSUBL


推荐阅读