Calculating Occupancy in hospital from dates with time.

放肆的年华 提交于 2019-12-06 15:13:58

Logic is to add 1 hour (i.e. 60*60 seconds) to Adm time (which is of POSIXct type) and compare it with Disc time.

First & last is added for cases wherein multiple rows are there for an ID. Then the earliest Adm and latest Disc time will only be considered per ID.


library(tidyverse)

df %>%
  group_by(ID) %>%
  mutate(occupancy = ifelse(last(Disc) > first(Adm) + 60*60, 1, 0))

which gives

     ID Adm                 Disc                occupancy
  <dbl> <dttm>              <dttm>                  <dbl>
1   101 2012-01-12 00:52:00 2012-01-12 02:00:00      1.00
2   102 2012-01-12 00:55:00 2012-01-12 02:59:00      1.00
3   103 2012-02-12 01:35:00 2012-01-12 03:01:00      0   
4   104 2012-02-12 03:24:00 2012-01-12 05:01:00      0   
5   105 2012-02-12 04:24:00 2012-01-12 06:01:00      0   
6   106 2012-02-12 05:24:00 2012-01-12 08:01:00      0   
7   107 2012-02-12 05:28:00 2012-01-12 08:01:00      0  


Sample data:

df <- structure(list(ID = c(101, 102, 103, 104, 105, 106, 107), Adm = structure(c(1326309720, 
1326309900, 1328990700, 1328997240, 1329000840, 1329004440, 1329004680
), class = c("POSIXct", "POSIXt"), tzone = ""), Disc = structure(c(1326313800, 
1326317340, 1326317460, 1326324660, 1326328260, 1326335460, 1326335460
), class = c("POSIXct", "POSIXt"), tzone = "")), .Names = c("ID", 
"Adm", "Disc"), row.names = c(NA, -7L), class = "data.frame")

We can try

library(dplyr)
library(lubridate)

df %>% group_by(ID) %>% 
       mutate(`Stay In (Hours)` = hour(Disc) - hour(Adm), Occupancy = ifelse(hour(Disc) - hour(Adm) > 1, 1, 0)) 
       %>% ungroup()

#But notice that `hour` consider the hour's part of the time only as shown below, which may lead to misleading results:
hour(as.POSIXct(c("2012-01-12 01:40:00"))) - hour(as.POSIXct(c("2012-01-12 00:50:00")))
[1] 1

The correct answer I hope so:

df %>% group_by(ID) %>% 
       mutate(`Stay In (Hours)` = round(difftime(Disc, Adm, units='hours'),2), 
               Occupancy = ifelse(difftime(Disc, Adm, units='hours') > 1, 1, 0)) %>% 
       ungroup()

  # A tibble: 7 x 5
     ID     Adm                Disc           `Stay In (Hours)`      Occupancy
    <dbl> <dttm>              <dttm>               <time>                <dbl>
1   101 2012-01-12 00:52:00 2012-01-12 02:00:00     1.13                  1.00
2   102 2012-01-12 00:55:00 2012-01-12 02:59:00     2.07                  1.00
3   103 2012-01-12 01:35:00 2012-02-12 03:01:00    745.43                 1.00
4   104 2012-01-12 03:24:00 2012-02-12 05:01:00    745.62                 1.00
5   105 2012-01-12 04:24:00 2012-02-12 06:01:00    745.62                 1.00
6   106 2012-01-12 05:24:00 2012-02-12 08:01:00    746.62                 1.00
7   107 2012-01-12 05:28:00 2012-02-12 08:01:00    746.55                 1.00
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!