1

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

loris
  • 450
  • 8
  • 20

2 Answers2

3

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

Community
  • 1
  • 1
Christoph_J
  • 6,804
  • 8
  • 44
  • 58
  • This is exactly what I need. Somehow I overlooked `strptime`. I actually don't really need the milliseconds, since the values are in general of the order of hours, but it's nice to know how to do it. – loris May 22 '12 at 12:56
  • @loris Glad I could help. If your question is answered thereby, could you mark it as accepted so it will be off the list of open questions? – Christoph_J May 22 '12 at 14:34
2

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.

sus_mlm
  • 1,144
  • 12
  • 17