R Date conversion

I am new to R and I have a data frame with date time as a variable. For each hour, the temperature of each day is recorded, and the time of the date is in the format YYYY-MM-DD 00:00:00. Now I would like to convert the time to a factor between 0 and 23 every day. So, for each day, my new column should have factors from 0 to 23. Can anyone help me with this? My 2015-01-01 00:00:00 should give me 0, and 2015-01-01 01:00:00 should give me 1 and so on. Also mine 2015-01-02 00:00:00 should be 0 again.

+3


source to share


4 answers


Using the sample data, one way would be as follows.



mydf <- data.frame(id = c(1,1,1,2,2,1,1),
                   event = c("start", "valid", "end", "start", "bad", "start", "bad"),
                   time = as.POSIXct(c("2015-05-16 20:46:53", "2015-05-16 20:46:56", "2015-05-16 21:46:59",
                                   "2015-05-16 22:46:53", "2015-05-16 22:47:00", "2015-05-16 22:49:05",
                                   "2015-05-16 23:49:09"), format = "%Y-%m-%d %H:%M:%S"),
                   stringsAsFactors = FALSE)

library(dplyr)
mutate(mydf, group = factor(format(time, "%H")))

#  id event                time group
#1  1 start 2015-05-16 20:46:53    20
#2  1 valid 2015-05-16 20:46:56    20
#3  1   end 2015-05-16 21:46:59    21
#4  2 start 2015-05-16 22:46:53    22
#5  2   bad 2015-05-16 22:47:00    22
#6  1 start 2015-05-16 22:49:05    22
#7  1   bad 2015-05-16 23:49:09    23

      

+1


source


You can convert a timestamp to an object POSIXlt

. After that, you can get this hour directly like this:



> timestamp <- as.POSIXlt("2015-01-01 00:00:00")
> timestamp
[1] "2015-01-01 MYT"
> timestamp$hour
[1] 0

      

+4


source


Answer by type using POSIXlt

is probably the best option, but here on a regular path:

> times <- c("2015-01-01 00:00:00", "2015-01-01 01:00:00", "2015-01-02 00:00:00")
> regmatches(times, regexpr("(?<=-\\d{2} )\\d{2}", times, perl=TRUE))
[1] "00" "01" "00"

      

With the clock extracted, you can make it factors or integers as needed.

+1


source


@Sairam, besides using @jazzurro 'dplyr' (which, like jazzurro, is often used by R-insitas) ... in the future, if you want / need a simple and powerful way to manipulate dates, you are encouraged to check out the other package: "lubridate ".

lubridate makes it easy to work with dates. Hope this helps and is the best for your project.

+1


source







All Articles