Erik Rasmussen
Erik Rasmussen

Reputation: 331

R Convert Chr String to Minutes & Seconds

I have a data set with times as strings representing minutes and seconds in the format mm:ss.s. It currently looks like:

"00:14.3"

Is there an easy way to convert this to times so that I can work with the data (plot etc)?

I have tried the Chron package, but this seems to require the string to be hh:mm:ss unless I've misunderstood

Upvotes: 2

Views: 2243

Answers (1)

jacobw125
jacobw125

Reputation: 136

You should be able to use strptime with a custom format string like so:

> strptime("00:14.3", format="%M:%OS")
[1] "2016-08-24 00:00:14 PDT"

Note that this will create a full datetime object using your current date and timezone. To see that the fractional second has been preserved, make sure your options(digits.secs) is set like this:

> options(digits.secs=2)
> strptime("00:14.3", format="%M:%OS")
[1] "2016-08-24 00:00:14.30 PDT"

You can adjust the date and timezone manually or with the strptime options. Depending on how you're using this, you can always format that back out into a string (reproduced here to prove no information was lost in the conversion):

> strftime(t, format="%M:%OS")
[1] "00:14.30"

Upvotes: 2

Related Questions