当前时间的最大功能

时间:2019-07-10 21:40:31

标签: r date posixct

如何创建一个具有时间后一天当前最高价的列?我使用了pmax,但没有帮助。

> df
             date_time  Price
1 2018-02-01 18:13:17 3178.5
2 2018-02-01 18:13:13 3179.0
3 2018-02-01 18:13:13 3178.5
4 2018-02-01 18:13:13 3178.5
5 2018-02-01 18:13:09 3178.5
6 2018-02-01 18:13:00 3178.5
7 2018-02-01 18:12:54 3179.5
8 2018-02-01 18:12:43 3179.5

我正在尝试这样做。

> mutate(df, high_day = ?)
            date_time  Price high_day
1 2018-02-01 18:13:17 3179.5   3179.5
2 2018-02-01 18:13:13 3179.0   3179.0
3 2018-02-01 18:13:13 3178.5   3179.0
4 2018-02-01 18:13:13 3179.0   3179.0
5 2018-02-01 18:13:09 3178.5   3178.5
6 2018-02-01 18:13:00 3178.5   3178.5
7 2018-02-01 18:12:54 3178.5   3178.5
8 2018-02-01 18:12:43 3178.5   3178.5

用于复制:

structure(list(data_hora = structure(c(1517508797, 1517508793, 
1517508793, 1517508793, 1517508789, 1517508780, 1517508774, 1517508763, 
1517508763, 1517508763, 1517508763, 1517508757, 1517508756), class = c("POSIXct", 
"POSIXt"), tzone = ""), Preco = c(3178.5, 3179, 3178.5, 3178.5, 
3178.5, 3178.5, 3179.5, 3179.5, 3179.5, 3179.5, 3179, 3179, 3179.5
)), row.names = 38:50, class = "data.frame")

1 个答案:

答案 0 :(得分:4)

这是怎么回事:

library(lubridate)
df %>%
  arrange(date_time) %>%
  group_by(date = as.Date(date_time)) %>%
  mutate(day_high = cummax(Price))