2013-07-09 1 views
0

기존 그룹을 기반으로 새 열, 생성 :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은 N이어야합니다.

누구나 SAS에서 어떻게 달성 할 수 있습니까? 정말 고맙게 생각합니다 :

+0

보고서를 만들 때 무엇을 사용하고 있습니까? – Joe

답변

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; 
+0

이 작품! 당신의 도움을 주셔서 감사합니다:) – Nip

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; 
0

편집 : 키스의 대답은 더 간단하고 깨끗합니다. 데이터가 이미 이름순으로 정렬되어 있고 데이터 집합이 큰 경우에만 다른 방식이 필요하지 않으므로 내 접근 방식을 사용하는 것이 좋습니다. 그렇지 않으면, 키이스의 접근 방식을 고수하십시오.

가정 데이터가 이미 이름으로 정렬됩니다 :

*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; 
관련 문제