如何按日期从 Dataframe 中获取多个每日值的最大值(总和)?

uinbv5nw  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(118)

我试图利用每日总和值作为绘图的参考(作为堆叠面积图中y轴的最大值)。如果每个日期有一个值,那么我将简单地使用max(data$value),但由于每个日期有多个值,我想知道如何获得最大的每日总和值。下面我提供了我使用的数据的简单版本:

df = data.frame(Date = c(rep(as.Date("2021-01-01"), 4), rep(as.Date("2021-01-02"), 4)),
                Group = c("A", "B", "C", "D", "A", "B", "C", "D"),
                Value = c(1:4, 2:5))
df
max(df$value)
> df
        Date Group Value
1 2021-01-01     A     1
2 2021-01-01     B     2
3 2021-01-01     C     3
4 2021-01-01     D     4
5 2021-01-02     A     2
6 2021-01-02     B     3
7 2021-01-02     C     4
8 2021-01-02     D     5
> max(df$Value)
[1] 5

理想情况下,我希望输出如下所示:

> max_by(data = df, Value, by = Date)
[1] 14

我知道这不是一个真实的的命令,我已经尝试使用dplyr和aggregate没有成功。

rjzwgtxy

rjzwgtxy1#

试试看

library(dplyr)# version >= 1.1.0
df %>% 
  reframe(Value = sum(Value), .by = Date) %>% 
   reframe(Value = max(Value))

或在base R

max(aggregate(Value ~ Date, df, sum)$Value)
[1] 14
rdrgkggo

rdrgkggo2#

我只是对使用评论和其他答案中建议的dplyr的细微变化感到好奇:

library(dplyr)

df = data.frame(Date = c(rep(as.Date("2021-01-01"), 4), rep(as.Date("2021-01-02"), 4)),
                Group = c("A", "B", "C", "D", "A", "B", "C", "D"),
                Value = c(1:4, 2:5))

set.seed(1)
rows <- sample(1:nrow(df), 1E5, replace = T)

df <- df[rows,]

library(microbenchmark)

(bench <- microbenchmark(
  df %>% 
    reframe(Value = sum(Value), .by = Date) %>% 
    reframe(Value = max(Value)),
  df %>% 
    summarize(Value = sum(Value), .by = Date) %>% 
    summarize(Value = max(Value)),
  df %>% group_by(Date) %>% 
    summarize(daily=sum(Value)) %>% 
    slice_max(daily, n=1),
  df %>% 
    summarize(daily=sum(Value), .by = Date) %>% 
    slice_max(daily, n=1)
)
)
ggplot2::autoplot(bench)

输出

在我的计算机上,summarizereframe稍微快一点,但并不明显。有趣的是,使用group_by而不是目前实验性的参数.by更慢:

Unit: milliseconds
                                                                                     expr
           df %>% reframe(Value = sum(Value), .by = Date) %>% reframe(Value = max(Value))
       df %>% summarize(Value = sum(Value), .by = Date) %>% summarize(Value = max(Value))
 df %>% group_by(Date) %>% summarize(daily = sum(Value)) %>% slice_max(daily,      n = 1)
        df %>% summarize(daily = sum(Value), .by = Date) %>% slice_max(daily,      n = 1)
      min       lq     mean   median       uq     max neval cld
 5.239101 5.452101 6.415455 5.649851 6.009101 15.4273   100 ab 
 5.180101 5.392100 5.984885 5.589701 5.874251 13.3959   100 a  
 7.551001 7.951001 8.613906 8.161901 8.510801 16.9265   100   c
 5.302501 5.564851 6.802251 5.896051 6.439151 16.6487   100  b

相关问题