2014-02-22 68 views
1

如何找到SAS中最大值的記錄?我有以下結構的數據集:在SAS中找到最大值的記錄

age name 
12 joe 
15 jane 
3 bob 
14 rick 

我想找個「名」的這「年齡」是最大的值(在這個例子 - 「簡」)。

我嘗試這樣做:

data max; 
    set ages_data; 
    if age > max_age then do; 
     max_age = age; 
    max_name = name; 
    end; 
    retain max_:; 
    keep max_:; 
run; 

這是基於什麼我發現這裏: https://communities.sas.com/message/170554

,但它並沒有爲我工作......我究竟做錯了什麼?

感謝

回答

3

你的代碼是好的 - 但輸出的所有記錄,我假設你希望只有一個?請嘗試以下變化:

這種方法
data max; 
    set ages_data end=lastobs; /* identify last record */ 
    if age > max_age then do; 
     max_age = age; 
     max_name = name; 
    end; 
    retain max_:; 
    keep max_:; 
    if lastobs then output; /* only output last record */ 
run; 

的一個缺點是,它只會輸出名稱的第一個值,對於給定的最長期限。該年齡可能有多個名稱值。下面的方法可以爲您的用途更爲強勁:

proc sql; 
create table max as 
    select name, age 
    from ages_data 
    where age= (select max(age) from ages_data); 

在情況下,它是有用的 - 這裏的datalines來進行測試:

data ages_data; 
infile cards; 
input age name $; 
cards; 
12 joe 
15 jane 
3 bob 
14 rick 
;run; 
+0

謝謝!這正是我需要的 - 完美的作品 –