将多行合并为一个时间间隔 [英] combine multiple rows into one time interval
本文介绍了将多行合并为一个时间间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,它由许多贴有标签的动物访问饲养员的日期和时间组成.看起来像这样-
I have a data frame which is made up of the date and time a number of tagged animals visited a feeder. it looks like this -
ID date_time
A 2019-11-02 08:07:47
B 2019-11-02 08:07:48
A 2019-11-02 08:07:49
A 2019-11-02 08:07:50
A 2019-11-02 08:09:12
A 2019-11-02 08:09:13
B 2019-11-02 08:09:17
我想将彼此在n秒内记录的所有数据点都集中到一行中,这样看起来-
I'd like to lump all data points recorded within n seconds of each other into a single row so that it looks like this -
ID start_date_time. end_date_time
A 2019-11-02 08:07:47 2019-11-02 08:07:50
B 2019-11-02 08:07:48 2019-11-02 08:07:48
A 2019-11-02 08:09:12 2019-11-02 08:09:13
B 2019-11-02 08:09:17 2019-11-02 08:09:47
我尝试使用Lubridate失败.
I have tried using Lubridate with no success.
谢谢
推荐答案
可能您可以这样做(N = 10s):
Possibly you can do it this way (N = 10s):
library(tidyverse)
dat %>%
group_by(ID) %>%
mutate(
events = cut(date_time, '10 s', labels = F)
) %>%
group_by(events, add = T) %>%
summarise(
start_date_time = min(date_time),
end_date_time = max(date_time)
) %>%
ungroup() %>%
select(-events)
# # A tibble: 4 x 3
# ID start_date_time end_date_time
# <chr> <dttm> <dttm>
# 1 A 2019-11-02 08:07:47 2019-11-02 08:07:50
# 2 A 2019-11-02 08:09:12 2019-11-02 08:09:13
# 3 B 2019-11-02 08:07:48 2019-11-02 08:07:48
# 4 B 2019-11-02 08:09:17 2019-11-02 08:09:17
数据:
structure(list(
ID = c("A", "B", "A", "A", "A", "A", "B"),
date_time = structure(
c(
1572678467,
1572678468,
1572678469,
1572678470,
1572678552,
1572678553,
1572678557
),
class = c("POSIXct", "POSIXt"),
tzone = ""
)
),
row.names = c(NA,-7L),
class = "data.frame")
这篇关于将多行合并为一个时间间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文