0

我目前正在使用 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,它等于最高记录的pct标志name。例如,A 的 name_flag 应该是 Y,B 的 name_flag 应该是 N。

谁能给我一点打击如何在SAS中实现这一点?真的很感激:)

4

3 回答 3

2

这里有一个稍微简单的解决方案。

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;
于 2013-07-10T08:29:53.937 回答
0

您可能需要对此进行调整,因为我没有运行 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;
于 2013-07-09T21:26:45.237 回答
0

编辑:基思的答案更简单、更干净。只有当您的数据已经按名称排序并且数据集很大时,我才会建议采用我的方法,因为它不需要另一种排序。否则,请坚持 Keith 的方法。

假设数据已经按名称排序:

*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;
于 2013-07-09T21:44:27.067 回答