r - 如何从 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
第一行。
之后我想找到一分钟的起始价格,所以这一分钟的第一个价格,最终价格以及最高和最低价格......另外你会看到Amount
MINUTE 和这些值,我想在这一分钟内计算它们的总和。
非常重要的是,结果中的秒数设置为零。所以这里的结果应该是:
Time Start End Low High Amount
1999-01-04 14:11:00 220 215 200 221 700
谢谢!
解决方案
组合Date
和Time
列以获得时间戳。用于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
推荐阅读
- php - json解析错误意外eof土耳其字符
- python - Sklearn 变换错误:预期 2D 数组,得到 1D 数组
- php - 即使 sendmail 工作,WordPress 也无法发送电子邮件
- swift4 - truncatingRemainder(dividingBy: ) 返回非零余数,即使数字是完全可除的
- django - 如何向 Django Oscar 注册合作伙伴发送有关已下订单的电子邮件?
- reactjs - ReactJS 表单验证瑞典社会安全号码
- c# - Microsoft.NETCore.Platforms 无法安装,因为它与您的任何项目都不兼容
- azure-functions - 同一功能应用内的不同绑定
- c# - 在将python代码转换为C#期间,hmacsha编码成为一个问题
- html - 如何将值从 html 传递到 django 中查看?