R

时间:2017-11-15 17:11:09

标签: r time-series aggregate cut

我的数据集由多个观察结果组成,超过3列(时间,价格和数量),如下所示,

time                price   volume
2017-11-15 9:35:11  301.1   1.1
2017-11-15 9:35:09  300.9   3.0
2017-11-15 9:35:07  300.8   1.4 
2017-11-15 9:35:06  300.9   0.1
2017-11-15 9:35:01  301.0   0.6

我想首先将数据剪切24小时,然后为每个24小时的时段添加音量,并在数据汇总时获取。

我尝试过以下操作(初始数据集在代码中称为“mydf”),

##sum the volume over periods of 24h
mydf_volume_24h <- data.frame (volume = tapply (cbind (mydf$volume), list (cut (mydf$time, breaks="24 hours")), sum))

##bind the previous df with the prices for each time label
mydf_24h <- setNames (cbind (rownames (mydf_volume_24h), mydf_volume_24h, row.names = NULL), c("time", "volume"))

mydf <- mydf %>% 
select(-volume)

mydf_24h <- merge (mydf, mydf_volume_24h, by = "time")

除了(可能)不是最好/最有效的方法之外,这段代码的问题不会产生,因为代码的第一部分给出了24小时的音量总和,但是用时间23:00:00,这在我的数据集中并不总是存在。

我所说的是切断24小时但是给我一个最接近24小时的观察的(实际)时间。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:1)

这可能不是您想要的,但根据您的描述,我收集到您想要将每个独特日的音量相加,并获得每个独特日的最大时间。如果这确实是你想要的,那么下面应该可以得到你的聚合数据框:

library(dplyr)
library(stringr)
library(lubridate)

df <- tibble(time = c(
             "2017-11-15 9:35:11",
             "2017-11-15 9:35:09",
             "2017-11-15 9:35:07",
             "2017-11-15 9:35:06",
             "2017-11-15 9:35:01",
             "2017-11-16 9:36:12",
             "2017-11-16 9:35:09",
             "2017-11-16 9:35:07",
             "2017-11-16 9:35:06",
             "2017-11-16 9:35:01"
             ),
             price = c(301.1, 300.9, 300.8, 300.9, 301.0,
                       302, 303, 304, 305, 306),
             volume = c(1.1, 3.0, 1.4, 0.1, 0.6,
                        1.4, 3.4, 1.5, 0.5, 0.6)
)

df %>% mutate(time = ymd_hms(time)) %>% 
        mutate(day = str_extract(time, "^\\S+"))  %>% 
        group_by(day) %>% 
        summarize(volume = sum(volume), maxTime = max(time))