首页 文章

在ddply中进行汇总时获取which.max的行名

提问于
浏览
0

我有以下数据,想要获得每年最高收盘价的最新日期 .

> 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 回答

  • 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 并使用它来轻松获取每个"Year"的"Close"最大时的行名称(日期) .

    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
    

相关问题