如果两组之间的距离在一定范围内,则在 R 中合并 rleid 分组

Combine rleid grouping in R if two groups are within certain distance from each other

我有一个监测患者生命体征变化的数据框。

然后使用交通灯系统(绿色、琥珀色和红色)对读数进行分类。

我目前正在使用 rleid 函数将组 ID 变量添加到我的数据框中。

然后我可以分离数据在红色类别中的出现次数,并且可以执行以下操作:

  1. 算出每个事件持续了多长时间

  2. 最小和最大读数等。

但是,我想合并在 12 小时内发生的所有红色类别(46 个数据点)。

举个例子:

Date=seq(as.POSIXct("2015-01-01 00:00:00"), as.POSIXct("2015-01-31 23:45:00"), by="15 min")
Data=c(rnorm(750,1,2),rnorm(100,4,2), rnorm(10,1,1),rnorm(50,4,2.5),rnorm(500,0,1),rnorm(600,6,2),rnorm(26,1,2),rnorm(940,6.5,2))
Class=c(rep("Green",750), rep("Red",100),rep("Green",10),rep("Red",50), rep("Green",500),rep("Red",600),rep("Green",26),rep("Red",940))

DF=data.frame(Date,Data,Class)
library(data.table)
library(ggplot2)
DF$GroupID=rleid(DF$Class)

ggplot(DF,aes(Date,Data,colour=Class,group=1))+geom_line()

在我的数据框中,我有 4 个红色簇,

但我希望只有两个 'red' 组,因为集群之间的数据点少于 46 个 'green'。

有什么方法可以指定吗?

我们可以利用绿组和红组的行数,如果绿组的行数小于46,就改成红

为了确保上一个组是'Red',我们可以添加一列来告诉我们上一个组

的'Class'
## One way to do this: 
## - get the first row for each group, then shift it back one to give us the class for the previous row
## - then join it all back together
dt_previous <- DF[order(Date), .I[1], by=.(GroupID)]
dt_previous[, V1 := V1 - 1]

## Get the previous Class according to the new V1/row index
dt_previous[ , previous_class :=  c(NA, DF[dt_previous$V1, as.character(Class)]) ]
## Join the 'previous_class' onto DF
DF <- dt_previous[, .(GroupID, previous_class)][ DF, on=c("GroupID")]

## define the number of rows for each group
DF[, nRows := .N, by=.(GroupID)]

## Update 'Green' to 'Red' where nRows < 46
DF[ nRows < 46 & Class == "Green" & previous_class == "Red", Class := "Red"]

## Redefine the groups
DF[, GroupID := rleid(Class)]

ggplot(DF, aes(Date, Data, colour=Class, group=1)) + geom_line()