r - 如何根据字符串变量的一部分重新组合因子水平?
问题描述
如果后续点之间的时间差大于某个阈值,我会拆分一些数据,并重命名发生拆分的 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 也是如此。
我只需要在执行缝合时识别 _ 之前的因子水平的东西,但我不确定如何。
解决方案
推荐阅读
- python-2.7 - Python 全局变量在函数中不可用
- python - Count and sum numbers by name
- javascript - 如何让 IDE 了解来自 JavaScript CDN 的符号信息?
- typescript - 我无法获得 json 格式的 multitem AsyncStorage React native
- security - GPG --decrypt 无法识别 --passphrase 选项
- postgresql - Postgresql:创建一个具有唯一值不区分大小写的文本字段,citext vs nondeterministic collation
- javascript - javascript - 从 javascript 对象中查找嵌套属性
- python-3.x - 如何在 Python 上使用 SoX 获取 MP3 文件的持续时间
- javascript - 单击时将 Bootstrap Dropdown 值重置为默认值
- discord.py - 放大默认表情符号 discord.py