[R] A problem with string handling to make a time duration
Franklin Bretschneider
bretschr at xs4all.nl
Tue May 5 12:26:22 CEST 2015
Hello gavinr,
> I have a character string that represents a time duration. It has an hours
> minutes seconds structure(ish) but with letters denoting units (H,M or S) no
> leading zeros and no placeholder at all where one or other of the units are
> not required.
>
> It looks like this:
>
> t<-c("10H20M33S","1H1M","1M","21M9S","2H55S" ))
> df<-data.frame(t)
> df
>
> #ideally should look like:
> t2<-c("10:20:33","01:00:01","00:01:00","00:21:09","02:00:55")
> df2<-data.frame(t2)
> df2
>
> I need to get it into hours minutes and seconds either in time format or as
> a string with leading zeros and all three time units represented in each
> one, as in df2. The data, part of a very large dataset, are for onward use
> and processing in a GIS application. I’ve messed about with string handling
> statements in SQL to no avail, but wondered if R would be a better bet?
> I’ve had a look at some of the commands in stringr, but am unsure how to
> operationalise a solution using this package. Any advice is welcome.
>
This can be done easily with the substring function, e.g.
# say:
string="12H15M45S"
#then pick:
h=substr(string,1,2)
m=substr(string,4,5)
# and join again:
newstr = paste(h,m,sep=":")
# etcetera
Success and
Best regards,
Frank
--
Franklin Bretschneider
Dept of Biology
Utrecht University
bretschr at xs4all.nl
More information about the R-help
mailing list