Calculating time slept

I am in the process of calculating time slept from Bed.time and Waking.up.time, these two columns are in a larger data set.

I transform them into a new data set and convert them to numerical data, ommitting NAs

bed <- data.frame(gsub(":","",as.character($Bed.time)))
lapply(bed, as.numeric)

wake <- data.frame(gsub(":","",as.character($Waking.up.time)))
lapply(wake, as.numeric)

timing <-data.frame(bed,wake)

Below is where have encountered a problem, I don’t believe my function(y) works:

# convert columns to seconds
convert =, lapply(timing, lubridate::seconds))

sleeping<- function(x){
  (as.numeric(substring(1,2)) * 60) + as.numeric(substring(3,4))
sleeping2<- function(y){
  (as.numeric(substring(1,2)) * 60) - as.numeric(substring(3,4))

In the ifelse statement if the value of Wake is larger then Bed, my function(x) is applied and Wake(x[2]) – Bed(x[1]). With my y function I am trying to do the opposite Bed(x[1]) – Wake(x[2]).

# get time diff
timing$time_slept <- ifelse(timing$Wake > timing$Bed, apply(convert, 1, function(x) x[2] - x[1]), apply(convert, 1, function(y) y[1] - y[2]))

However, data output (timing) looks like this:
timing output

In somecases my calculations are a success but in others, as you can see the values are minused from eachother in the wrong order e.g. row 1 2345-0645=1700

>Solution :

1 – Transform character vectors to a date-time object

bed <- lubridate::parse_date_time(bed, '%H%M')
wake <- lubridate::parse_date_time(wake, '%H%M')

2 – Calculate time difference

time_diff <- wake - bed

3 – Correct negative values by adding 24 hours.

time_diff_corrected <- ifelse(time_diff < 0, time_diff + 24, time_diff)

Leave a Reply