如何计算R中给定时间段内的最大值?

问题描述 投票:0回答:1

我从 MySQL 获取了数据,我正在尝试将其可视化并找出一些答案。 使用 R 进行统计。

最终产品是每次价格变化(=行)的%折扣。

这是我的数据集的示例。

     itemId pricehis           timestamp
1  69295477     1290 2022-04-12 04:42:53
2  69295624     1145 2022-04-12 04:42:53
3  69296136     3609 2022-04-12 04:42:54
4  69296607      855 2022-04-12 04:42:53
5  69295291     1000 2022-04-12 04:42:50
6  69295475     4188 2022-04-12 04:42:52
7  69295614     1145 2022-04-12 04:42:51
8  69295622     1290 2022-04-12 04:42:50
9  69295692     3609 2022-04-12 04:42:49
10 69295917     1725 2022-04-12 04:42:48
11 69296090     2449 2022-04-12 04:42:53
12 69296653     1145 2022-04-12 04:42:51
13 69296657     5638 2022-04-12 04:42:48
14 69296661     1725 2022-04-12 04:42:51
15 69296696      710 2022-04-12 04:42:51

我一直停留在计算的一个部分——6 个月内每个产品 ID 的最大值。

在数据集中,特定产品 ID 的行具有不同的价格值和不同的时间戳。我需要找到不超过 6 个月的给定行的最大值。

所需折扣的计算公式为:

Discount grouped by itemId =  1 - pricehis / max(pricehis in the last 6 months)

目前我无法解决第二部分 - 过去 6 个月的价格。 - 我需要一个新列,其中 itemId 在过去 6 个月内具有最大“pricehis”。 也可以称为区间最大值。

我可以按 itemId 将其分组,但我不知道如何添加最多 6 个月的条件。

关于如何获得这个有什么建议吗?

r max
1个回答
0
投票

我喜欢

slider::slide_index_dbl
这类事情。这里选择了一些假数据来演示 6mo 窗口:

data.frame(itemId = rep(1:2, each = 6),
           price = floor(100*cos(0:11)^2),
           timestamp = as.Date("2000-01-01") + 50*(0:11)) -> df

我们可以从

df
开始,按照itemId进行分组,然后计算,然后应用窗口函数。 (请注意,
slider
要求数据在每组内按日期排序。)

library(dplyr).  
library(lubridate) # for `%m-%`, to get sliding months (harder than it sounds!)
df %>%     
  group_by(itemId) %>%
  mutate(max_6mo = slider::slide_index_dbl(.x = price,     # based on price...
                                           .i = timestamp, # and timestamp...
                                           .f = max,       # what's the max...
                                           .before = ~.x %m-% months(6))) %>% # over the last 6mo
  mutate(discount = 1 - price / max_6mo) %>%               # use that to calc discount
  ungroup()

结果

# A tibble: 12 × 5
   itemId price timestamp  max_6mo discount
    <int> <dbl> <date>       <dbl>    <dbl>
 1      1   100 2000-01-01     100   0     
 2      1    29 2000-02-20     100   0.71  
 3      1    17 2000-04-10     100   0.83  
 4      1    98 2000-05-30     100   0.0200
 5      1    42 2000-07-19      98   0.571    # new max since >6mo since 100
 6      1     8 2000-09-07      98   0.918 
 7      2    92 2000-10-27      92   0     
 8      2    56 2000-12-16      92   0.391 
 9      2     2 2001-02-04      92   0.978 
10      2    83 2001-03-26      92   0.0978
11      2    70 2001-05-15      83   0.157    # new max since >6mo since 92
12      2     0 2001-07-04      83   1 
© www.soinside.com 2019 - 2024. All rights reserved.