如何使用 dplyr 和 lubridate 添加依赖于最后一行的行?

How to add row which depends on last row using dpylr and lubridate?

Open/Close 分钟价格数据。下一分钟的开盘价总是等于前一分钟的收盘价。示例数据集:

dt                   open  close
1998-01-02 09:30:00  100   101
1998-01-02 09:31:00  101   102
...
1998-01-02 15:59:00  105   106

在最后一行之后我想像这样添加另一行:

dt                   open  close
1998-01-02 09:30:00  100   101
1998-01-02 09:31:00  101   102
...
1998-01-02 15:59:00  105   106
1998-01-02 16:00:00  106   NA

即时间戳增加一分钟,开盘等于上一分钟收盘,收盘为NA。我的幼稚方法 没有 工作:

library(lubridate)
library(dplyr)

data <- add_row(data, dt = max("dt") + minute(1), open = close[[n()]])

有什么想法吗?

首先,您应该使用 minutes(创建时间段)而不是 minute(用于获取日期时间的分钟部分)。其次,在 add_row 中,您不能像在其他 dplyr 函数中那样使用字符串或列名引用 data 中的列。

一种方法是:

> data <- data %>% add_row(dt = max(.$dt) + minutes(1), open = last(.$close))
> data
# A tibble: 4 x 3
  dt                   open close
  <dttm>              <int> <int>
1 1998-01-02 09:30:00   100   101
2 1998-01-02 09:31:00   101   102
3 1998-01-02 15:59:00   105   106
4 1998-01-02 16:00:00   106    NA

其中样本 data 是:

> dput(data)
structure(list(dt = structure(c(883733400, 883733460, 883756740
), class = c("POSIXct", "POSIXt"), tzone = "UTC"), open = c(100L, 
101L, 105L), close = c(101L, 102L, 106L)), row.names = c(NA, 
-3L), class = c("tbl_df", "tbl", "data.frame"))

我们也可以使用bind_rows

library(tidyverse)
data %>% 
  summarise(dt = max(dt) + minutes(1), open = last(close)) %>% 
  bind_rows(data, .)
# A tibble: 4 x 3
#  dt                   open close
#  <dttm>              <int> <int>
#1 1998-01-02 09:30:00   100   101
#2 1998-01-02 09:31:00   101   102
#3 1998-01-02 15:59:00   105   106
#4 1998-01-02 16:00:00   106    NA