首页 > 解决方案 > 如何从 R 中的时间提取价格并汇总每分钟的值?

问题描述

我有一个对我来说有点难以处理的数据框:

Date      Time         Price   Amount
19990104  14:11:14.34  220     100
19990104  14:11:21.21  200     150
19990104  14:11:36.35  221     200
19990104  14:11:45.45  202     150
19990104  14:11:56.11  215     100

我尝试创建一个完整的时间:"%Y-%m-%d %H:%M:%S" e.g. 1999-01-04 14:11:14第一行。

之后我想找到一分钟的起始价格,所以这一分钟的第一个价格,最终价格以及最高和最低价格......另外你会看到AmountMINUTE 和这些值,我想在这一分钟内计算它们的总和。

非常重要的是,结果中的秒数设置为零。所以这里的结果应该是:

Time        Start End  Low High  Amount
1999-01-04 14:11:00  220   215  200 221   700 

谢谢!

标签: rdataframedatetimetimestampcalculation

解决方案


组合DateTime列以获得时间戳。用于floor_date将时间戳向下舍入到分钟级别并汇总数据。

library(dplyr)
library(tidyr)
library(lubridate)

df %>%
  unite(Timestamp, Date, Time, sep = ' ') %>%
  mutate(Timestamp = ymd_hms(Timestamp)) %>%
  arrange(Timestamp) %>%
  group_by(Timestamp = floor_date(Timestamp, 'mins')) %>%
  summarise(Start = first(Price), 
            End = last(Price), 
            Low = min(Price), 
            High = max(Price), 
            Amount = sum(Amount))

#  Timestamp           Start   End   Low  High Amount
#  <dttm>              <int> <int> <int> <int>  <int>
#1 1999-01-04 14:11:00   220   215   200   221    700

推荐阅读