0

I need count how many days for months one hospital bed was busy. So, I have start and end dates of patient admitted.

One example

df <- data.frame(pac=c("A","B","C"),
                 start=c("2015-10-30","2015-11-08","2015-12-08"),
                 end=c("2015-11-10","2016-01-02","2016-03-05"))

I wait to find one data.frame according to

Ano Mes Value  
15  OUT  2     
15  NOV  33    
15  DEZ  55    
16  JAN  33    
16  FEV  29    
16  MAR  5

How can I do it in R?

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • 1
    Does this answer help? https://stackoverflow.com/questions/6243088/find-out-the-number-of-days-of-a-month-in-r –  Jul 13 '18 at 12:54
  • 3
    Possible duplicate of [Find out the number of days of a month in R](https://stackoverflow.com/questions/6243088/find-out-the-number-of-days-of-a-month-in-r) – Random Cotija Jul 13 '18 at 13:04

1 Answers1

1

A shorter solution is probably possible, but I find this very readable :) The abbreviated month is in my locale (dutch)... it changes depending on your PC-settings.. or you can set it inline (?lubridate::month)

library(tidyverse)
library(lubridate)
#create a vector of all dates within the given ranges
v <- apply( df, 1, function(x) {seq( as.Date(x[2], format = "%Y-%m-%d"), as.Date(x[3], format = "%Y-%m-%d"), by ="day" )}) %>%
  unlist() %>%
  as.Date( origin = "1970-01-01" ) 

#put the dates in a data.frame, use lubridate to extract year and month-data
df2 <- data.frame ( date = v ) %>%
  mutate( Ano = lubridate::year( date ) ) %>%
  mutate( Mes = lubridate::month( date, abbr = TRUE, label = TRUE ) ) %>%
  group_by( Ano, Mes ) %>%
  summarise( Value = n() ) %>%
  select( Ano, Mes, Value)

# > df2
# # A tibble: 6 x 3
# # Groups:   Ano [2]
#     Ano Mes   Value
#    <dbl> <ord> <int>
# 1  2015 okt       2
# 2  2015 nov      33
# 3  2015 dec      55
# 4  2016 jan      33
# 5  2016 feb      29
# 6  2016 mrt       5
Wimpel
  • 26,031
  • 1
  • 20
  • 37