I would like to transform the variable "Time" (which is in chr format) into hour format. The data looks like this:
There are several packages that deal with time format in R. lubridate
is probably the friendliest currently.
horas <- paste0(1:18,':00')
> horas
[1] "1:00" "2:00" "3:00" "4:00" "5:00" "6:00" "7:00" "8:00" "9:00"
[10] "10:00" "11:00" "12:00" "13:00" "14:00" "15:00" "16:00" "17:00" "18:00"
> class(horas)
[1] "character"
library(lubridate)
horas.ld <- hm(horas)
> horas.ld
[1] "1H 0M 0S" "2H 0M 0S" "3H 0M 0S" "4H 0M 0S" "5H 0M 0S" "6H 0M 0S"
[7] "7H 0M 0S" "8H 0M 0S" "9H 0M 0S" "10H 0M 0S" "11H 0M 0S" "12H 0M 0S"
[13] "13H 0M 0S" "14H 0M 0S" "15H 0M 0S" "16H 0M 0S" "17H 0M 0S" "18H 0M 0S"
> class(horas.ld)
[1] "Period"
attr(,"package")
[1] "lubridate"
> horas.ld[7] - horas.ld[1]
[1] "6H 0M 0S"
For those who like to use data.table
, it has its own classes for date and time:
library(data.table)
> as.ITime(horas)
[1] "01:00:00" "02:00:00" "03:00:00" "04:00:00" "05:00:00" "06:00:00"
[7] "07:00:00" "08:00:00" "09:00:00" "10:00:00" "11:00:00" "12:00:00"
[13] "13:00:00" "14:00:00" "15:00:00" "16:00:00" "17:00:00" "18:00:00"
> class(as.ITime(horas))
[1] "ITime"