【问题标题】:Combine rleid grouping in R if two groups are within certain distance from each other如果两个组彼此相距一定距离,则在 R 中合并 rleid 分组
【发布时间】:2016-03-29 08:41:38
【问题描述】:

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

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

我目前正在使用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 个红色簇,

但我希望只有两个“红色”组,因为集群之间的“绿色”数据点少于 46 个。

有什么方法可以指定吗?

【问题讨论】:

    标签: r dataframe data.table grouping cluster-analysis


    【解决方案1】:

    我们可以利用Green Group和Red Group各自的行数,只要Green group的行数小于46,就改为Red

    为了确保前一个组是“红色”,我们可以添加一个列来告诉我们前一个组的“类”

    ## 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()
    

    【讨论】:

    • 这是个好主意 - 谢谢。我想知道是否可以添加前一组必须为红色才能应用此规则的约束?这样,例如,如果课程从“绿色”变为“橙色”,我希望它保持“绿色”,即使这只是为了一小部分点。
    • @sym246 - 当然!请看我的编辑。可能有一种更优雅的方式,但这应该会让你继续前进
    • 谢谢@Symbolix,太好了!
    • @sym246 - setDT(DF) 不需要分配给任何东西,因为它会更新 DF by reference
    • 这不再起作用,抛出错误:“[.data.frame(DF, order(Date), .I[1], by = .(GroupID)) 中的错误:未使用的参数 (by = .(GroupID))"
    猜你喜欢
    • 2021-10-19
    • 2017-07-06
    • 1970-01-01
    • 2013-12-07
    • 2016-12-30
    • 2018-07-09
    • 1970-01-01
    • 2016-01-05
    • 2020-03-02
    相关资源
    最近更新 更多