【问题标题】:substituting values in column under if-condition SAS在 if-condition SAS 下替换列中的值
【发布时间】:2021-12-21 22:34:48
【问题描述】:

我对 sas 还很陌生,我正在努力解决这个问题。我有两张桌子A和B。 第一个收集有关客户的购买信息和他们购买的特定产品的信息

一个

Customer_id product_code
1111111 12345
1111111 34523

第二个是某种字典,即包含新旧代码,旧代码是键,新代码是更新版本。

B

old new
34523 22256
89765 76576

我的目标是在表 A 中更新所有对旧代码的引用及其更新(新)版本。最后 A 应该是这样的

Customer_id product_code
1111111 12345
1111111 22256

我会在这个例子中采用的方法如下(伪代码)

if A.product_code in B.old then
   A.product_code = B.new
else
   nothing

但我在使用 sas 合成器来实现它时有点挣扎。

我真的希望我的问题足够清楚,如有必要,请毫不犹豫地要求进一步澄清。

感谢任何愿意参与的人

【问题讨论】:

  • 那些是数字变量还是字符变量?
  • 为什么要更改现有数据集?您不应该制作一个具有 PRODUCT_CODE 新值的新数据集吗?为什么要搞乱你的输入?

标签: if-statement sas sas-macro


【解决方案1】:

怎么样

data a;
input Customer_id product_code;
datalines;
1111111 12345
1111111 34523
;

data b;
input old new;
datalines;
34523 22256
89765 76576
;

proc sql;
   update a
   set product_code = 
      (select new from b
      where a.product_code = b.old)
   where exists (
      select 1
      from b
      where a.product_code = b.old)
   ;
quit;

【讨论】:

  • 非常感谢 :) 至于所使用的语法:update a (ok) select new from b where a.product_code = b.old 如果 a 有旧代码,则更新它 where exists (...) 您是否创建了一个布尔值来判断是否产品代码等于旧代码?为什么需要这一步?
  • @JacquesLeen where 子句限制了哪些行被更新 - 即只有那些需要更新的行。存在测试是找到这些行的最便宜的方法
【解决方案2】:

一种非常 SAS 的方式是使用MODIFY 语句和哈希查找。

data master;
  modify master;
  if _n_ = 1 then do;
    declare hash mappings(dataset:'code_changes(rename=new_code=code)');
    mappings.defineKey('old_code');
    mappings.defineData('code');
    mappings.defineDone();
    call missing(old_code);
  end;

  if mappings.find(key:code)=0 then replace;
run;

另一种MODIFY 方法是使用SET 语句读取更改。

此示例需要主表上的索引。

proc sql;
  create index code on master;

data master;
  set mappings;

  reset = 1;
  do until (_iorc_);
    code = old_code;
    modify master key=code keyreset=reset;

    if _iorc_ = 0 then do;
      code = new_code;
      replace;
    end;
    reset = 0;
  end;

  _error_ = 0;
run;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多