Working with time in R
I am really afraid to work with time in R and wondered if anyone could help.
For a sample data frame:
df <- structure(list(Time = structure(1:9, .Label = c("07:55:40", "07:55:50",
"07:56:00", "07:56:10", "07:56:20", "07:56:30", "07:56:40", "07:56:50",
"07:57:00"), class = "factor")), .Names = "Time", class = "data.frame", row.names = c(NA,
-9L))
I am using the following lines of code to convert time to R format recognizes (start.time) and then adds 10 seconds to start.time to get end.time.
df$start.time <- strptime(df$Time, "%H:%M:%S") ##Correct
df$end.time <- df$start.time + 10
R automatically adds today's date to both the start and end. This is not what I wanted - as long as I understand that R prefers to have a reference date, this is not required for my purposes.
How can I exclude a date?
source to share
Try the "times"
class in chron. It represents once in a fraction of a day, so 1 second 1 / (24 * 60 * 60)
. Please note that all times must be less than 24:00:00:
> library(chron)
> transform(df, Time = times(Time) + 10 / (24 * 60 * 60))
Time
1 07:55:50
2 07:56:00
3 07:56:10
4 07:56:20
5 07:56:30
6 07:56:40
7 07:56:50
8 07:57:00
9 07:57:10
source to share
I don't understand why you created time, with factor as class. Anyway, here is my solution with packages lubridate
.
First convert at time the period
class with the function hms
and then just add 10 seconds with the function seconds
.
library(lubridate)
df$Time <- hms(df$Time)
df[2] <- df[1] + seconds(10)
head(df, 2)
Time Time.1
1 7H 55M 40S 7H 55M 50S
2 7H 55M 50S 7H 55M 60S
source to share