问题
I have some data in which I have multiple observations of the same event. Based on a threshold of time, I want to condense the observations. But I want to know how many I am condensing (i.e. how many observations become one). I'm not sure how to loop through my dataframe in such a way to do that.
I've tried writing a for loop, if statements, while statements, and have searched tirelessly on google and on stack overflow. Nothing seems to relate to what I need to do.
here is a subset of my data:
structure(list(date.time = structure(c(1465877617, 1465877774,
1465877816, 1465877844, 1465912214, 1465912806, 1465912862, 1465914033
), class = c("POSIXct", "POSIXt"), tzone = "America/New_York"),
time = structure(1:8, .Label = c("00:13:37", "00:16:14",
"00:16:56", "00:17:24", "09:50:14", "10:00:06", "10:01:02",
"10:20:33"), class = "factor"), X = c(1, 1, 1, 1, 1, 1, 1,
1), diff_time1 = structure(c(157, 42, 28, 34370, 592, 56,
1171, 2820), class = "difftime", units = "secs"), diff_time2 = c(FALSE,
FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE), new = c("start",
"include", "include", "end", "start", "include", "end", "start-end"
)), row.names = c(NA, 8L), class = "data.frame")
The goal is to get it to look like below, but with an additional column of sample size for each "smushed" observation:
structure(list(n = 1:8, end = structure(c(1465877844, 1465912862,
1465914033, 1465916853, 1465921999, 1465928992, 1465933159, 1465937668
), class = c("POSIXct", "POSIXt")), start = structure(c(1465877617,
1465912214, 1465914033, 1465916853, 1465921999, 1465928647, 1465932867,
1465937418), class = c("POSIXct", "POSIXt")), date = structure(c(16966,
16966, 16966, 16966, 16966, 16966, 16966, 16966), class = "Date")), row.names = c(NA,
-8L), class = c("tbl_df", "tbl", "data.frame"))
回答1:
library(dplyr); library(lubridate)
df %>%
mutate(time_since_last = (date.time - lag(date.time, default = first(date.time))) / dminutes(1)) %>%
mutate(group = 1 + cumsum(time_since_last > 15)) %>% # How many times was there a 15min+ gap? Each new one increments "group"
group_by(group) %>%
summarize(first = min(date.time), # or first(date.time) if sorted
last = max(date.time), # or last(date.time) if sorted
count = n())
## A tibble: 3 x 4
# group first last count
# <dbl> <dttm> <dttm> <int>
#1 1 2016-06-14 00:13:37 2016-06-14 00:17:24 4
#2 2 2016-06-14 09:50:14 2016-06-14 10:01:02 3
#3 3 2016-06-14 10:20:33 2016-06-14 10:20:33 1
来源:https://stackoverflow.com/questions/55562991/is-there-a-way-to-loop-through-data-based-on-factor-in-a-column-and-add-up-the-n