我目前在报表上使用SAS工作的新列,其中有这样一个表如下:SAS基于现有的组
Name Country Pct Flag
A USA 40 Y
A CAN 30 N
A CHN 30 N
B BRA 70 N
B JAP 30 Y
我想产生一个新列Name_Flag
,这等于name
的最高记录pct
的标志。例如,A的name_flag应该是Y,而B应该是N.
任何人都可以给我一点点击如何在SAS中实现这一点?真的很感谢:)
我目前在报表上使用SAS工作的新列,其中有这样一个表如下:SAS基于现有的组
Name Country Pct Flag
A USA 40 Y
A CAN 30 N
A CHN 30 N
B BRA 70 N
B JAP 30 Y
我想产生一个新列Name_Flag
,这等于name
的最高记录pct
的标志。例如,A的name_flag应该是Y,而B应该是N.
任何人都可以给我一点点击如何在SAS中实现这一点?真的很感谢:)
稍微简单的解决方案:
假设数据是通过名字已经被排序。
data have;
input Name $ Country $ Pct Flag $;
datalines;
A USA 40 Y
A CAN 30 N
A CHN 30 N
B BRA 70 N
B JAP 30 Y
;
run;
proc sort data=have;
by name descending pct;
run;
data want;
set have;
by name descending pct;
retain name_flag;
if first.name then name_flag=flag;
run;
这个工程!谢谢你的帮助:) – Nip
您可能需要调整这一点,因为我没有SAS会话运行测试。
proc sort data = flagData;
by pct descending;
run;
data flagDataDone;
retain nameWithHighestPct;
set flagData;
if _n_ = 1 then do;
nameWithHighestPct = name;
end;
name_flag = 'N';
if name = nameWithHighestPct then do;
name_flag = 'Y';
end;
drop nameWithHighestPct;
run;
编辑:基思的答案更简单,更清洁。只有当你的数据已经按名称排序并且数据集很大时,我会建议采取我的方法,因为它不需要其他排序。否则,坚持基思的方法。这里
*First we find the correct flag per group;
data BEST_PER_GROUP (keep=Name Name_Flag);
set DATASET;
by Name;
*Need to retain this until we looked at all candidates;
retain highest_pct 0;
retain Name_Flag '';
*Find the flag of the highest Pct;
if Pct > highest_pct then do;
highest_pct = Pct;
Name_Flag = Flag;
end;
*When having looked at all records for a given Name, output the result;
if last.Name then do;
output;
*Reset for next value group of Name;
highest_pct = 0;
Name_Flag = '';
end;
run;
*Merge it back with your data;
data DATASET;
merge DATASET BEST_PER_GROUP;
by Name;
run;
你用什么来创建你的报告? – Joe