Shoaibkhanz
Shoaibkhanz

Reputation: 2082

Arithmetic with Time in R

enter image description here

 dt$st<- substr(strptime(dt$LoginTime, format = "%H:%S"),12,20)

Using the above code I have extracted the time which is in Character Format, I wish to do arithmetic on it. such as if I want to multiply a column of numbers with above column, how to i do it?

Structure of LoginTime Column is :

structure(c(1505L, 231L, 1606L, 757L, 139L, 702L), .Label = c("0:00:01", 
"0:00:05", "0:00:06", "0:00:07", "0:00:10", "0:00:12", "0:00:13", 9:56:01", 
"9:56:31", "9:57:11", "9:57:39", "9:58:37"), class = "factor")

Upvotes: 1

Views: 1507

Answers (2)

David Arenburg
David Arenburg

Reputation: 92292

It seems like you can do some of the calculations with a small adjusment to your code. For example

To compute mean

substr(mean(strptime(dt$LoginTime, format = "%H:%S")), 12, 20)

To add 10 seconds to each row

substr(strptime(dt$LoginTime, format = "%H:%S") + 10, 12, 20)

To add a minute to each row

substr(strptime(dt$LoginTime, format = "%H:%S") + 60, 12, 20)

To add an hour

substr(strptime(dt$LoginTime, format = "%H:%S") + 3600, 12, 20)

To add two hours

substr(strptime(dt$LoginTime, format = "%H:%S") + 7200, 12, 20)

Upvotes: 1

Roland
Roland

Reputation: 132706

It seems like you have periods and not times. You could use package lubridate:

x <- factor(c("0:00:13", "9:56:01"))

library(lubridate)
y <- hms(x)
#[1] "13S"       "9H 56M 1S"

However, read help("period"):

Within a Period object, time units do not have a fixed length (except for seconds) until they are added to a date-time. The length of each time unit will depend on the date-time to which it is added. For example, a year that begins on 2009-01-01 will be 365 days long. A year that begins on 2012-01-01 will be 366 days long. When math is performed with a period object, each unit is applied separately. How the length of a period is distributed among its units is non-trivial. For example, when leap seconds occur 1 minute is longer than 60 seconds.

y*3
#[1] "39S"         "27H 168M 3S"

Upvotes: 1

Related Questions