【问题标题】:find max value in a data.frame by group and show its date as year-month-day按组在 data.frame 中查找最大值并将其日期显示为年-月-日
【发布时间】:2016-10-28 12:52:54
【问题描述】:

这是我的数据框:

df = read.csv(text = '"Date","Value","ID","WY"
                  1975-02-01,-1.16543693088,"Tweed",1975
                  1975-03-01,-1.05372283483,"Tweed",1975
                  1975-04-01,-1.06632370439,"Tweed",1975
                  1975-05-01,-1.18903485356,"Tweed",1975
                1992-05-01,-1.04737467143,"Ouse",1992
                1992-06-01,-1.4058281451,"Ouse",1992
                1992-07-01,-1.13608647243,"Ouse",1992
                1992-08-01,-0.802566581309,"Ouse",1992
                1992-09-01,-0.551433852821,"Ouse",1992
                1992-10-01,-0.625997598552,"Ouse",1993
                1992-11-01,-0.483559758609,"Ouse",1993
                1992-12-01,-0.792013395632,"Ouse",1993
                1993-01-01,-0.754618121962,"Ouse",1993
                1993-02-01,-1.2504282139,"Ouse",1993
                1996-01-01,-0.945410385985,"Trent",1996
                1996-02-01,-0.84249575782,"Trent",1996
                1996-03-01,-1.10332425045,"Trent",1996
                1996-04-01,-1.22634133042,"Trent",1996
                1996-05-01,-1.2335181635,"Trent",1996
                1996-06-01,-1.23451130358,"Trent",1996
                1996-07-01,-1.25902677738,"Trent",1996
                1996-08-01,-1.13068733413,"Trent",1996', header = TRUE)

我需要找到每个 ID 和 WY 组的年度最大值。

下面的代码很容易做到这一点,但它的输出只显示每个年度最大值的年份,而我也对相对的月份和日期感兴趣:

df_AMAX = aggregate(df$Value, by = list(df$WY, df$ID), max)
colnames(df_AMAX) = c('Date', 'ID', 'Value')
print(df_AMAX)

 Date    ID      Value
1 1992  Ouse -0.5514339
2 1993  Ouse -0.4835598
3 1996 Trent -0.8424958
4 1975 Tweed -1.0537228

我的输出应该是:

 Date           ID      Value
1 1992-09-01  Ouse -0.5514339
2 1993-11-01  Ouse -0.4835598
3 1996-02-01  Trent -0.8424958
4 1975-03-01  Tweed -1.0537228

这应该是一件愚蠢的事情,但如果您有任何建议,请告诉我。 谢谢

【问题讨论】:

  • 试试library(data.table);setDT(df)[, .SD[which.max(Value)] , .(ID, WY)]
  • 太棒了@akrun。请发表你的答案。

标签: r dataframe aggregate


【解决方案1】:

subsetave 一起使用。请注意,传递给ave 的函数返回一个逻辑值,但ave 会将其强制转换为Value 的类,因此我们使用 !!让它再次合乎逻辑。没有使用任何包。

mx_all <- function(x) if (length(x)) x == max(x)
subset(df, !!ave(Value, ID, WY, FUN = mx_all))

mx_first <- function(x) if (length(x)) seq_along(x) == which.max(x)
subset(df, !!ave(Value, ID, WY, FUN = mx_first))

这些对样本输入给出相同的答案,并且如果每个组中都有唯一的最大值,则始终给出相同的答案,但如果组中有多个最大值,则第一个给出所有最大值,第二个给出首先。

【讨论】:

    【解决方案2】:

    当然也有dplyr 解决方案:

    df %>% 
      group_by(WY, ID) %>% 
        summarise(
          Value = max(Value),
          Date = Date[which.max(Value)]) %>% 
      ungroup() %>% 
       select(ID:Date)
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 1970-01-01
      • 2021-08-17
      • 1970-01-01
      • 2012-02-03
      相关资源
      最近更新 更多