【问题标题】:How to extract prices from time in R and summarize values per Minute?如何从 R 中的时间提取价格并汇总每分钟的值?
【发布时间】:2021-10-27 07:31:28
【问题描述】:

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

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

然后我想找到一分钟的START-Price,所以这一分钟的第一个Price,END-Price以及最高和最低价格...... 另外,您会看到Amount 和分钟的这些值,我想计算它们在这一分钟的总和。

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

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

谢谢!

【问题讨论】:

    标签: r dataframe datetime timestamp calculation


    【解决方案1】:

    结合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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 1970-01-01
      • 2017-11-20
      • 2018-09-15
      相关资源
      最近更新 更多