loris
loris

Reputation: 469

Converting time interval in R

My knowledge and experience of R is limited, so please bear with me.

I have a measurements of duration in the following form:

d+h:m:s.s

e.g. 3+23:12:11.931139, where d=days, h=hours, m=minutes, and s.s=decimal seconds. I would like to create a histogram of these values.

Is there a simple way to convert such string input into a numerical form, such as seconds? All the information I have found seems to be geared towards date-time objects.

Ideally I would like to be able to pipe a list of data to R on the command line and so create the histogram on the fly.

Cheers

Loris

Upvotes: 1

Views: 1913

Answers (2)

Christoph_J
Christoph_J

Reputation: 6884

Another solution based on SO:

op <- options(digits.secs=10)
z <- strptime("3+23:12:11.931139", "%d+%H:%M:%OS")
vec_z <- z + rnorm(100000)
hist(vec_z, breaks=20)

Short explanation: First, I set the option in such a way that the milliseconds are shown. Now, if you type z into the console you get "2012-05-03 23:12:11.93113". Then, I parse your string into a date-object. Then I create some more dates and plot a histogramm. I think the important step for you is the parsing and strptime should help you with that

Upvotes: 3

sus_mlm
sus_mlm

Reputation: 1154

I would do it like this:

str = "3+23:12:11.931139"    
result = sum(as.numeric(unlist(strsplit(str, "[:\\+]", perl = TRUE))) * c(24*60*60, 60*60, 60, 1))
> result
[1] 342731.9

Then, you can wrap it into a function and apply over the list or vector.

Upvotes: 2

Related Questions