我正在寻找一个与Excel中的"VLOOKUP"函数类似的SAS代码。
我有两张桌子:table_1有一个ID列,其中还有一些其他列,共有10行。Table_2有两列:ID和Definition,共50行。我想在表_1中定义一个新的变量"Definition",并从表_2中查找ID值。
除了合并,我还没有真正尝试过其他任何东西。但是merge保留了table_2中所有额外的40个变量,这不是我喜欢的。
谢谢,SE
最简单的方法是在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;
这里有一个非常有用(而且通常非常快速)的方法,专门用于1:1匹配,这就是VLOOKUP
所做的。使用匹配变量和查找结果创建Format或Informat,并将put
或input
作为主表中的匹配变量。
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;