首页 > 解决方案 > 如何根据字符串变量的一部分重新组合因子水平?

问题描述

如果后续点之间的时间差大于某个阈值,我会拆分一些数据,并重命名发生拆分的 ID

# prep the data
ID = c(rep("A",5), rep("B",5))
DateTime = c("2014-09-25 08:39:45", "2014-09-25 08:39:48", "2014-09-25 08:40:44", "2014-09-25 09:04:00","2014-09-25 09:04:10", "2014-09-25 08:33:32", "2014-09-25 08:34:41", "2014-09-25 08:35:24", "2014-09-25 09:04:00", "2014-09-25 09:04:09")
df = data.frame(ID,DateTime, stringsAsFactors = FALSE)
df$DateTime<-as.POSIXct(df$DateTime, tz = "UTC")

# split if the time difference is greater than 100 and rename the IDs

library(dplyr)
df %>%
  group_by(ID) %>%
  mutate(timeDiff = c(NA, difftime(tail(DateTime, -1), head(DateTime, -1), units="sec"))) %>%
  mutate(newID = paste(ID, cumsum(!is.na(timeDiff) & timeDiff > 100),sep = "_")) %>%
  ungroup()

在此之后,我运行一些基于 newID 列的数据函数。

但我想在此之后再次将我的数据缝合在一起。因此,A_0、A_1 将作为 A 重新粘在一起,对于 B 也是如此。

我只需要在执行缝合时识别 _ 之前的因子水平的东西,但我不确定如何。

标签: rstringdatetimedplyrcumsum

解决方案


推荐阅读