-2

there.

I know this might be a silly question but really appreciated an answer. I have two columns naming "start time" and "end time" in the format as "HH:MM:SS", what I need to do is converting them into decimal values and join them together.

More specifically,here is an example: column "start time": 09:00:00 column "end time": 10:00:00 final result: 9-10

I know how to do that in mysql, but any solutions how to get it done in R? Thanks very much.

Alina HE
  • 31
  • 1
  • 5

1 Answers1

2

Here's a function to convert time to decimal, assuming you want decimal hour:

# fake data
asdf <- c("12:34:56","12:00:00","06:01:49","1:30:00")

hhmmss2dec <- function(x) {
  xlist <- strsplit(x,split=":")
  h <- as.numeric(sapply(xlist,"[",1))
  m <- as.numeric(sapply(xlist,"[",2))
  s <- as.numeric(sapply(xlist,"[",3))
  xdec <- h+(m/60)+(s/60/60)
  return(xdec)
}

hhmmss2dec(asdf)
12.582222 12.000000  6.030278  1.500000

Or this, which could work for what you're looking for...

starts <- c("10:00:00","12:34:56")
ends <- c("12:00:00","14:20:00")

hourthing <- function(start,end) {
  startlist <- strsplit(start,split=":")
  endlist <- strsplit(end,split=":")
  hstart <- sapply(startlist,"[",1)
  hend <- sapply(endlist,"[",1)
  out <- paste(hstart,hend,sep="-")
  return(out)
}

hourthing(starts,ends)
"10-12" "12-14"
avallecam
  • 669
  • 8
  • 8
Matt Tyers
  • 2,125
  • 1
  • 14
  • 23