Skip to content
Prev 387602 / 398502 Next

How to average minutes per hour per month in the form of '# hours #minutes'

Hi,
As you still seem to be asking for an answer, the following code may help.

# begin with a minimal data frame
patdb<-data.frame(patno=paste0("p",sample(100:300,200,TRUE)),
 date=c(paste(2020,11,sort(sample(1:31,66,TRUE)),sep="-"),
 paste(2020,12,sort(sample(1:31,67,TRUE)),sep="-"),
 paste(2021,01,sort(sample(1:31,67,TRUE)),sep="-")),
 consdur=sample(15:40,200,TRUE))
patdb$date<-as.Date(patdb$date,"%Y-%m-%d")
patdb$year<-format(patdb$date,"%Y")
patdb$month<-as.numeric(format(patdb$date,"%m"))
patdb$weekday<-as.numeric(format(patdb$date,"%u"))
patdb$week<-as.numeric(format(patdb$date,"%W"))
# first do the easy one
minperday<-by(patdb$consdur,patdb$date,sum)
hrperday<-minperday%/%60
minperday<-minperday%%60
# now the hard one - first get the number of days per week
daysperweek<-by(patdb$consdur,patdb$week,length)
# correct for weeks less than seven days
minperweek<-by(patdb$consdur,patdb$week,sum)*7/daysperweek
hrperweek<-minperweek%/%60
minperweek<-minperweek%%60
minpermonth<-by(patdb$consdur,patdb$month,sum)
hrpermonth<-minpermonth%/%60
minpermonth<-minpermonth%%60
daystr<-paste(names(minperday),"#",hrperday,"#",minperday)
weekstr<-paste(names(minperweek),"#",hrperweek,"#",minperweek)
monthstr<-
 paste(month.name[as.numeric(names(minpermonth))],"#",
 hrpermonth,"#",minpermonth)

Further enhancements to the three vectors of output strings are
possible as are various summary measures.

Jim
On Fri, Mar 26, 2021 at 6:22 PM Dr Eberhard W Lisse <nospam at lisse.na> wrote: