[R] Convert string to time

Dirk Eddelbuettel edd at debian.org
Sun Apr 12 21:15:38 CEST 2009


On 12 April 2009 at 21:00, Peter Kraglund Jacobsen wrote:
| One variable contains values (1.30 - one hour and thirty minutes, 1.2
| (which is supposed to be 1.20 - one hour and twenty minutes)). I would
| like to convert to a minute variable so 1.2 is converted to 80
| minutes. How?

The littler sources have a script pace.r (see below) that does some simple
transformations so that it can come up with min/mile and min/km expression
given a distance (in miles) and a time (in fractional minutes) as 'read' --
eg in the example below 76.02 stands for 1 hour 16 minutes and 2 seconds.

In a nutshell, you divide and keep score of remainders.

There may be more compact ways to do this---pace.r is a pretty linear
translation of an earlier Octave script pace.m.

Hth, Dirk

edd at ron:~> pace.r 10.20 76.02
Miles    : 10.2
Time     : 76.02
Pace/m   :  7 min 27.25 sec
Pace/km  :  4 min 37.91 sec
edd at ron:~>
edd at ron:~> cat bin/pace.r
#!/usr/bin/env r
#
# a simple example to convert miles and times into a pace
# where the convention is that we write e.g. 37 min 15 secs
# as 37.15 -- so a call 'pace.r 4.5 37.15' yields a pace of
# 8.1667, ie 8 mins 16.67 secs per mile

if (is.null(argv) | length(argv)!=2) {

  cat("Usage: pace.r miles time\n")
  q()

}

dig <- 6

rundist <- as.numeric(argv[1])
runtime <- as.numeric(argv[2])

cat("Miles\t :", format(rundist, digits=dig), "\n")
cat("Time\t :", format(runtime, digits=dig), "\n")

totalseconds <- floor(runtime)*60 + (runtime-floor(runtime))*100
totalsecondspermile <- totalseconds / rundist
minutespermile <- floor(totalsecondspermile/60)
secondspermile <- totalsecondspermile - minutespermile*60

totalsecondsperkm <- totalseconds / (rundist * 1.609344)
minutesperkm <- floor(totalsecondsperkm/60)
secondsperkm <- totalsecondsperkm - minutesperkm*60

pace   <- minutespermile + secondspermile/100
pacekm <- minutesperkm + secondsperkm/100

cat(sprintf("Pace/m\t : % 2.0f min %05.2f sec\n",
            minutespermile, secondspermile))
cat(sprintf("Pace/km\t : % 2.0f min %05.2f sec\n",
            minutesperkm, secondsperkm))
edd at ron:~>



| ______________________________________________
| R-help at r-project.org mailing list
| https://stat.ethz.ch/mailman/listinfo/r-help
| PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
| and provide commented, minimal, self-contained, reproducible code.

-- 
Three out of two people have difficulties with fractions.




More information about the R-help mailing list