Home > Software engineering >  Convert Time String to Numeric in R
Convert Time String to Numeric in R

Time:03-24

I have the following data, it is a character and in the format of minutes:seconds. I want to convert his number to a numeric value (single number). I have tried several as.POSIXct methods to no avail. Assistance is a greatly appreciated.

Data:

[1] "1255:03" "1183:56" "1170:11" "1155:17" "1126:17"
  [6] "1111:59" "1092:17" "1077:20" "1070:12" "1061:30"
 [11] "1056:48" "1056:11" "1053:28" "1025:58" "1021:31"
 [16] "1014:47" "1012:41" "1012:31" "1001:07" "1000:56"
 [21] "997:16"  "983:41"  "982:49"  "981:25"  "980:36" 
 [26] "979:59"  "978:23"  "975:46"  "971:05"  "969:50" 
 [31] "1434:11" "1363:32" "1264:08" "1212:19" "1152:53"
 [36] "1133:25" "1120:22" "1117:58" "1109:20" "1106:18"
 [41] "1103:39" "1083:36" "1078:10" "1072:39" "1069:13"
 [46] "1062:31" "1060:13" "1053:48" "1044:37" "1042:09"

CodePudding user response:

We can use period_to_seconds

library(lubridate)
period_to_seconds(ms("1255:03"))
[1] 75303

CodePudding user response:

Here is another option using gsub str2lang eval (but not as efficient as @akrun's method)

> s <- c("1255:03", "1183:56")

> eval(str2lang(sprintf("c(%s)", toString(gsub(":", "*60 ", s)))))
[1] 75303 71036
  • Related