Home > Net >  Calculating time slept
Calculating time slept

Time:11-05

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(proj.data$Bed.time)))
lapply(bed, as.numeric)
colnames(bed)[1]<-"Bed"
#View(bed)

wake <- data.frame(gsub(":","",as.character(proj.data$Waking.up.time)))
lapply(wake, as.numeric)
colnames(wake)[1]<-"Wake"
#View(wake)

timing <-data.frame(bed,wake)
#View(timing)
as.numeric(na.omit(timing$Bed))
as.numeric(na.omit(timing$Wake))

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

# convert columns to seconds
convert = do.call(data.frame, 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[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

CodePudding user response:

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)
  •  Tags:  
  • r
  • Related