【问题标题】:SAS Code that works like Excel's "VLOOKUP" function与 Excel 的“VLOOKUP”功能类似的 SAS 代码
【发布时间】:2013-06-26 17:00:01
【问题描述】:

我正在寻找与 Excel 中的“VLOOKUP”功能类似的 SAS 代码。

我有两张桌子: table_1 有一个 ID 列,其中包含 10 行的其他一些列。 Table_2 有两列:ID 和定义,共 50 行。我想在 table_1 中定义一个新变量“Definition”并从 table_2 中查找 ID 值。

除了合并之外,我还没有真正尝试过任何其他方法。但是合并保留了 table_2 中所有额外的 40 个变量,这不是我喜欢的。

谢谢,SE

【问题讨论】:

    标签: excel sas


    【解决方案1】:

    最简单的方法是在merge 语句中使用keep 选项。

    data result;
        merge table_1 (in=a) table_2 (in=b keep=id definition);
        by id;
        if a;
     run;
    

    另一种意味着您不必对数据集进行排序的方法是使用 proc sql。

    proc sql;
        create table result as
        select a.*,
               b.definition
        from table_1 a
        left join table_2 b on a.id = b.id;
    quit;
    

    最后,如果 table_2 很小,还有哈希表选项:

    data result;
        if _n_ = 1 then do;
            declare hash b(dataset:'table_2');
            b.definekey('id');
            b.definedata('definition');
            b.definedone();
            call missing(definition);
        end;
        set table_1;
        b.find();
    run;
    

    【讨论】:

    • 我无法让它工作。你能解释一下sql过程的select选项中的a是什么,b是什么?
    【解决方案2】:

    这是一种非常有用(而且通常非常快)的方法,专门用于 1:1 匹配,这就是 VLOOKUP 所做的。您可以在主表中使用匹配变量和查找结果以及 putinput 匹配变量创建格式或信息。

    data class_income;
    set sashelp.class(keep=name);
    income =  ceil(12*ranuni(7));
    run;
    
    
    data for_format;
    set class_income end=eof;
    retain fmtname 'INCOMEI';
    start=name;
    label=income;
    type='i'; *i=informat numeric, j=informat character, n=format numeric, c=format character;
    output;
    if eof then do;
     hlo='o'; *hlo contains some flags, o means OTHER for nonmatching records;
     start=' ';
     label=.;
     output;
    end;
    run;
    
    proc format cntlin=for_format;
    quit;
    
    data class;
    set sashelp.class;
    income = input(name,INCOMEI.);
    run;
    

    【讨论】:

      猜你喜欢
      • 2017-05-21
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 2013-05-04
      • 2011-04-01
      相关资源
      最近更新 更多