I am new to R and I have a data frame with date time as variable. For every hour each day temperature is recorded, and date time is in format of YYYY-MM-DD 00:00:00. Now I would like to convert the time into a factor ranging from 0 to 23 each day. So For each day my new column should have factors 0 to 23. Could anyone help me with this? My 2015-01-01 00:00:00, should give me 0, while 2015-01-01 01:00:00, should give me 1 and so on. Also my 2015-01-02 00:00:00 should be 0 again.
You can convert your timestamp into a POSIXlt
object. Once you have that, you can obtain the hour directly like this:
> timestamp <- as.POSIXlt("2015-01-01 00:00:00")
> timestamp
[1] "2015-01-01 MYT"
> timestamp$hour
[1] 0
Using a sample data, one way would be the following.
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
Tim's answer using POSIXlt
is probably the best option, but here's a regex way just in case:
> 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 extracted hours you can make them factors or integers as necessary.
@Sairam, in addition to @jazzurro's use of 'dplyr' (which, like jazzurro, many R-insitas routinely use)...in the future, if you need/want a simple & powerful way to manipulate dates, you're encouraged to gain familiarity with another package: 'lubridate.'
lubridate makes working with dates a snap. Hope this helps and best regards on your project.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.