Turning Chr into a team in R

Asked

Viewed 182 times

1

I would like to turn the variable "Time" (which is in Chr format) into time format. The data is like this:

inserir a descrição da imagem aqui

  • 1

    Welcome to Stackoverflow! Unfortunately, this question cannot be reproduced by anyone trying to answer it. Please, take a look at this link and see how to ask a reproducible question in R. So, people who wish to help you will be able to do this in the best possible way.

1 answer

2

There are several packages that handle hours format in R. lubridate is probably the most friendly 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"
  • @Erick-Kill Example data for your question is easy to generate, but here’s the advice: always post an example of your data in a format that is easily reproducible.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.