Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: how to resample a datetime variable at the millisecond level?

I have a dataframe like the following

library(dplyr)
library(lubridate)
time = c('2013-01-03 22:04:21.549', '2013-01-03 22:04:21.549', '2013-01-03 22:04:21.559', '2013-01-03 22:04:23.559' )
value = c(1,2,3,4)

data <- data_frame(time, value)
data <-data %>%  mutate(time = ymd_hms(time))

# A tibble: 4 × 2
                     time value
                   <dttm> <dbl>
1 2013-01-03 22:04:21.549     1
2 2013-01-03 22:04:21.549     2
3 2013-01-03 22:04:21.559     3
4 2013-01-03 22:04:23.559     4

I would like to resample this dataframe every 200 milliseconds.

That is, take the average of value every 200 milliseconds.

I know can use lubridate::floor_date(time, '1 second') up to the second precision, but not for milliseconds.

In the example above, row 1,2, and 3 should be grouped together while row 4 should be alone (note it is 2 seconds apart from the others).

Any ideas? Thanks!

like image 567
ℕʘʘḆḽḘ Avatar asked Oct 26 '25 12:10

ℕʘʘḆḽḘ


1 Answers

Since you used the [xts] tag, here's an xts solution:

options(digits.secs=6)
require(xts)
x <- xts(1:4, as.POSIXct(c('2013-01-03 22:04:21.549', '2013-01-03 22:04:21.549',
                           '2013-01-03 22:04:21.559', '2013-01-03 22:04:23.559')))
period.apply(x, endpoints(x, "ms", 200), mean)
#                         [,1]
# 2013-01-03 22:04:21.559    2
# 2013-01-03 22:04:23.559    4

Starting from your data object:

x <- with(data, xts(value, time))
period.apply(x, endpoints(x, "ms", 200), mean)
like image 76
Joshua Ulrich Avatar answered Oct 29 '25 04:10

Joshua Ulrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!