简体   繁体   中英

Aggregate data on daily intervals in R

My dataset is composed of several observations, over 3 columns (time, price and volume), as follows,

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

I want to start by cut the data by periods of 24h, adding the volume for each period of 24h and obtaining the at the time the data is aggregated.

I have tried by doing the following (the initial dataset is called "mydf" on the code),

##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")

The problem with this code, besides (probably) being not the best/efficient way, does not result since the first part of the code gives me the the sum of the volume for a period of 24h but labeling each sum with the time 23:00:00, which not always exists on my dataset.

What I entended is to cut over 24h periods but giving me the (real) time of an observation which is the closest to the period of 24h. Is there any way to do this?

This may not be exactly what you want, but from your description I gathered that you want to sum the volume for each unique day, along with getting the max time for each unique day. If that is indeed what you want the below should work to get your aggregate data frame:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM