dataframe - Handling integer times in R -
times in data frame recorded integers in: 1005,1405,745,1130,2030 etc. how convert these integers r understand , use in functions such strptime. in advance help
solution using strptime()
as pointed out psidom in comment, can convert integers character , use strptime()
:
int_times <- c(1005,1405,745,1130,2030) strptime(as.character(int_times), format="%h%m") ## [1] "2016-04-21 10:05:00 cest" "2016-04-21 14:05:00 cest" na ## [4] "2016-04-21 11:30:00 cest" "2016-04-21 20:30:00 cest"
however, can see, run trouble number has 3 digits. can around using formatc()
format integers character 4 digits , leading 0 (if needed):
char_times <- formatc(int_times, flag = 0, width = 4) char_times [1] "1005" "1405" "0745" "1130" "2030"
now, conversion works:
strptime(char_times, format="%h%m") ## [1] "2016-04-21 10:05:00 cest" "2016-04-21 14:05:00 cest" "2016-04-21 07:45:00 cest" ## [4] "2016-04-21 11:30:00 cest" "2016-04-21 20:30:00 cest"
note strptime()
returns posixct object involves time and date. since no data given, current day used. use paste()
combine times date:
strptime(paste("2010-03-21", char_times), format="%y-%m-%d %h%m") ## [1] "2010-03-21 10:05:00 cet" "2010-03-21 14:05:00 cet" "2010-03-21 07:45:00 cet" ## [4] "2010-03-21 11:30:00 cet" "2010-03-21 20:30:00 cet"
solution using lubridate::hm()
as suggested richard telford in comment, make use of lubridate's period
class, if prefer not have date involved. class periods of times , represent clock time, 10:23, period 10 hours, 23 minutes. however, using hm()
lubridate not work:
library(lubridate) hm(char_times) ## [1] na na na na na ## warning message: ## in .parse_hms(..., order = "hm", quiet = quiet) : ## strings failed parse
the reason without separator, not clear how these times should converted. hm()
expects representation has hours before minutes. "1005"
100 hours , 5 minutes 1 hour , 5 minutes. need introduce separation between hours , minutes, instance follows:
char_times2 <- paste(substr(char_times, 1, 2), substr(char_times, 3, 4)) hm(char_times2) ## [1] "10h 5m 0s" "14h 5m 0s" "7h 45m 0s" "11h 30m 0s" "20h 30m 0s"
note have again used fixed width string represantation char_times
, because hours given first 2 characters. makes easy use substr()
.
Comments
Post a Comment