0

I have a dataframe called "Camera_data" and a column called "Numeric_time"

My "Numeric_time" column is in character format and includes hours, minutes and seconds, it looks like this: 08:40:01

I need to remove the numbers that pertain to seconds and replace the semicolons with periods to make a decimal number for my time. I need it to look like this: 08.40 in order to turn my time into radians for an analysis I'm running.

I've looked for a few solutions in stringr, but so far can't work out how to consistently take off the last three characters. I think once I have removed the seconds and replaced the : with a . I can just use as.numeric to turn the character column into a numerical column, but would really appreciate any help!

Claire
  • 11
  • 5
  • Does this answer your question? [How to convert time (mm:ss) to decimal form in R](https://stackoverflow.com/questions/5186972/how-to-convert-time-mmss-to-decimal-form-in-r) – M Aurélio Feb 17 '23 at 17:24
  • @MAurélio OP refers to radians, not decimals. – jay.sf Feb 17 '23 at 18:45

2 Answers2

1

We could do

Camera_data$Numeric_time <- as.numeric(chartr(":", ".", 
    sub(":\\d{2}$", "", Camera_data$Numeric_time )))

Or use substr

Camera_data$Numeric_time <- substr(Camera_data$Numeric_time, 1, nchar(Camera_data$Numeric_time)-3)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Using gsub with two capture groups.

as.numeric(gsub('(\\d+):(\\d+).*', '\\1.\\2', x))
# [1]  8.40 18.41  0.00

Data:

x <- c('08:40:01', '18:41:01', '00:00:01')
jay.sf
  • 60,139
  • 8
  • 53
  • 110