0

What appears simple, is for me quite a brain teaser. I got this

times1 <- c(0000, 0720, 2315, 0600, 1150, NA, 0000)

and I want got transform this number in hours and mintues with the hm-function that I get an lubridate format.

Thank you very much for your help! Best wishes, Robin

2 Answers2

0

Try this option:

times1 <- c('0000', '0720', '2315', '0600', '1150', NA, '0000')
ts <- ifelse(is.na(times1),
             NA,
             paste0(substr(times1, 1, 2), ":", substr(times1, 3, 4), ":00"))
x <- hms(ts)
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thank you very much. However, I still get that message: In .parse_hms(..., order = "HMS", quiet = quiet) : Some strings failed to parse, or all strings are NAs Have you ever encountered that problem? – Robin Rosine Mar 13 '18 at 06:35
  • I just updated my answer, try it again. (Reload your page). – Tim Biegeleisen Mar 13 '18 at 06:35
  • Thanx for the update. Unfortantly I still get the same error message. Maybe it's something with my time settings? – Robin Rosine Mar 13 '18 at 06:41
  • I just updated again, I can't test at the moment unfortunately. – Tim Biegeleisen Mar 13 '18 at 06:42
  • Closer: "0::00" "72:0:00" "23:15:00" "60:0:00" "11:50:00" NA "0::00" Nice work with NA! I'm trying now to get rid of the :: – Robin Rosine Mar 13 '18 at 06:47
  • You have bad data. My answer would work if you actually had _strings_. You may not be able to fix it if you have numbers. By the way, there is no leading zero in `0720`, it is just `720`. – Tim Biegeleisen Mar 13 '18 at 06:52
0

since your aim is to convert to hours and minutes, you need to use the hm function and not the hms function:

times1 <- c('0000', '0720', '2315', '0600', '1150', NA, '0000')
hm(sub("(\\d{2})","\\1:",times1))
[1] "0S"         "7H 20M 0S"  "23H 15M 0S" "6H 0M 0S"   "11H 50M 0S"
[6] NA           "0S"        
Onyambu
  • 67,392
  • 3
  • 24
  • 53