0

I have a data frame in the time format. i need to change it to numeric data. I used the following format but i am not sure if it is correct since the values changes in numeric format.

Photoperiod
08:52:41
08:53:35
08:54:33
08:55:36
08:56:44
08:57:55
08:59:11
09:00:31
09:01:55
09:03:23
09:04:55
09:06:31
09:08:10
09:09:53
09:11:40

DF<- read.csv2(file="DF.csv")
DF.a <-as.POSIXct(DF, format = "%H:%M:%S")

library(data.table)

DF.B<- lapply(DF.a , function(x) as.numeric(as.ITime(x)) / 3600)
Jaap
  • 81,064
  • 34
  • 182
  • 193
Mori
  • 241
  • 1
  • 2
  • 10
  • 1
    Where's the problem? First two time have a difference of ~1 minute. This is 1/60 ~0.016. If you look at the difference between first two times it's 0.015. – Roman Luštrik Aug 19 '17 at 11:22
  • 1
    What values did you expect to see? The function `as.numeric(as.ITime(x))/3600` would give time in terms of number of hours (up to 24). You can check for example that `as.numeric(as.ITime("12:00:00"))/3600` returns 12, `as.numeric(as.ITime("23:59:59"))/3600` returns 23.99972, & so on. – Z.Lin Aug 19 '17 at 13:18
  • My data frame is the daylight data, so 14:25:30 means 14 hours and 25 min of daylight, i dont know if i use as.numeric(as.ITime(x))/3600 i crush my data or not. Just get confused. – Mori Aug 19 '17 at 15:26

1 Answers1

2

A (very) similar question was asked yesterday in the SO in portuguese. The answer by Marcus Nunes may give what you want.

Note that he calls the function HoraDecimal, portuguese for 'DecimalHour'.

HoraDecimal <- function(x){
  sum(unlist(lapply(strsplit(x, split=":"), as.numeric)) * c(1, 1/60, 1/3600))
}

x <-  "02:20:00"
HoraDecimal(x)
[1] 2.333333

y <-  "00:50:00"
HoraDecimal(y)
[1] 0.8333333

z <- "3:30:30"
HoraDecimal(z)
[1] 3.508333

I've made a suggestion in the comments section, to use sapply instead of unlist(lapply(...)). The following is such a version. With name changed to english.

DecimalHour <- function(x){
  sum(sapply(strsplit(x, split=":"), as.numeric) * c(1, 1/60, 1/3600))
}

DecimalHour(x)
DecimalHour(y)
DecimalHour(z)

The conversion method is the same, it's still Marcus' function and if you find it usefull the credits should go to him.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66