2015-08-08 59 views
0

我有以下數據,並且想知道Close在每年的最大值時的日期。在ddply中進行彙總時獲取which.max的行名

> str(ndvdf) 
'data.frame': 1374 obs. of 2 variables: 
$ Close: num 150 150 150 150 150 ... 
$ Year : num 2009 2009 2009 2009 2009 ... 
> head(ndvdf) 
      Close Year 
2010-01-04 150.34 2009 
2010-01-05 150.34 2009 
2010-01-06 150.34 2009 

我嘗試以下,但該行指數的回報,而不是日期和指標是每個年度的子集,因此很難用rownames得到的日期要麼。

> ddply(ndvdf, .(Year), summarise, MaxDate=which.max(Close)) 
    Year MaxDate 
1 2009  60 
2 2010  244 
3 2011  245 

如何從我的數據中獲取日期? 謝謝。

回答

1

下面是一些重複的樣品數據:

set.seed(19) 
df <- data.frame(Close = sample(150, 10), Year = sample(2000:2003, 10, TRUE)) 
rownames(df) <- Sys.Date() + 1:10 

我喜歡這裏使用data.table包。我們可以使用as.data.tablekeep.rownames = TRUE,並使用它輕鬆獲取「Close」在每個「Year」的最大值時的行名稱(日期)。

library(data.table) 
as.data.table(df, keep.rownames = TRUE)[, rn[which.max(Close)], keyby = Year] 
# Year   V1 
# 1: 2000 2015-08-13 
# 2: 2001 2015-08-17 
# 3: 2002 2015-08-16 
# 4: 2003 2015-08-18