2016-06-24 9 views
2

Angenommen, ich habe eine Datensatz D1 wie folgt:SAS für Szenario folgende (häufigster Beobachtung)

ID ATR1 ATR2 ATR3 
1  A  R  W 
2  B  T  X 
1  A  S  Y 
2  C  T  E 
3  D  U  I 
1  T  R  W 
2  C  X  X 

Ich möchte ein Datensatz D2 daraus erstellen, wie

ID ATR1 ATR2 ATR3 
1  A  R  W 
2  C  T  X 
3  D  U  I 

folgt Mit anderen Worten, der Datensatz D2 besteht aus eindeutigen IDs von D1. Für jede ID in D2 werden die Werte von ATR1-ATR3 als die häufigsten (der jeweiligen Variablen) unter den Datensätzen in D1 mit der gleichen ID ausgewählt. Zum Beispiel ID = 1 in D2 hat ATR1 = A (am häufigsten).

Ich habe eine Lösung, die sehr ungeschickt ist. Ich sortiere einfach dreimal Kopien des Datensatzes "D1" (nach ID und ATR1) und entferne Duplikate. Ich füge später die drei Datensätze zusammen, um zu bekommen, was ich will. Ich denke jedoch, dass es einen eleganten Weg dafür geben könnte. Ich habe etwa 20 solcher Variablen im ursprünglichen Datensatz.

Dank

Antwort

1
/* 
read and restructure so we end up with: 

id attr_id value 
1 1 A 
1 2 R 
1 3 W 
etc. 
*/ 

data a(keep=id attr_id value); 
length value $1; 
array attrs_{*} $ 1 attr_1 - attr_3; 
infile cards; 
input id attr_1 - attr_3; 
do attr_id=1 to dim(attrs_); 
    value = attrs_{attr_id}; 
    output; 
end; 
cards; 
1  A  R  W 
2  B  T  X 
1  A  S  Y 
2  C  T  E 
3  D  U  I 
1  T  R  W 
2  C  X  X 
; 
run; 

/* calculate frequencies of values per id and attr_id */ 
proc freq data=a noprint; 
tables id*attr_id*value/out=freqs(keep=id attr_id value count); 
run; 

/* sort so the most frequent value per id and attr_id ends up at the bottom of the group. 
    if there are ties then it's a matter of luck which value we get */ 
proc sort data = freqs; 
by id attr_id count; 
run; 

/* read and recreate the original structure. */ 
data b(keep=id attr_1 - attr_3); 
retain attr_1 - attr_3; 
array attrs_{*} $ 1 attr_1 - attr_3; 
set freqs; 
by id attr_id; 
if first.id then do; 
    do i=1 to dim(attrs_); 
     attrs_{i} = ' '; 
    end; 
end; 
if last.attr_id then do; 
    attrs_{attr_id} = value; 
end; 
if last.id then do; 
    output; 
end; 
run; 
Verwandte Themen