【问题标题】:Finding date differences between rows in R查找R中行之间的日期差异
【发布时间】:2021-08-26 15:03:57
【问题描述】:

我有一个如下所示的数据集: Hospital admissions

Id 是患者,遭遇是个别医院就诊。 STARTENC 是访问的开始。我想查找在 90 天内导致再次入院的患者的医院遭遇 - 我该怎么做?

我试过以下代码:

Readmission_time <- as.POSIXlt(visit1$STARTENC)
Readmission_time <- difftime(Readmission_time[1] , Readmission_time[2:length(visit1$STARTENC)])
Readmission_time <- ifelse(Readmission_time >= 30 & Readmission_time <= 90, 1, 0)

但它返回的观察结果比我的少。

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。
  • 能否请您使用dput(your_data) 提供您的数据样本。请不要使用数据图像,因为没有大量不必要的努力就无法使用它们。问题应该是可重复的reproducible examples

标签: r time difference


【解决方案1】:

首先,您应该确保您的数据按患者 ID 和 STARTENC 排序,以便能够将一行与下一行进行比较。 其次,您不能只将一条线与另一条线进行比较,因为两条线可能适用于不同的患者。

在 R 中,获得结果的一种方法是使用 data.table 包。

我在下面的代码中使用一个小型数据集演示了解决方案,其中有 4 位患者和 6 次遭遇。只有患者 A 必须在遭遇某些事件后的 90 天内回来。

library(data.table)

# build fake data
ids <- c('D', 'C', 'A', 'A', 'A', 'B')
starts <- c('2008-01-01', '2007-04-02', '2006-02-11', '2006-03-15', '2009-02-01', '2009-03-17')
# making sure it is ordered correctly
data <- data.table(Id=ids, STARTENC=starts)[order(Id, STARTENC)]

# converting strings to Date
data[, STARTENC := as.Date(STARTENC)]

# for every patient and encounter building a column that will contain the
# date of the NEXT patient's encounter. THe by=.(Id) is important here
data[, NEXTENC := shift(STARTENC, type = 'lead'), by=.(Id)]

# computing the delta between an encounter and the next
data[, DELTA := difftime(NEXTENC, STARTENC)]

# counting how many lines have a delta below 90
data[DELTA <= 90, .N]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2016-09-20
    • 1970-01-01
    相关资源
    最近更新 更多