1

I have a CSV with many values. Among them are times stored like this:

1:34.434

Using readr, I form them into a tibble, and use dplyr to cut out all the unnecessary rows and columns.

lapData <- read_csv("sampledata/sampledata.csv")
lapData <- dplyr::select(lapData, 
                         Driver, Lap, Penalty, 'Lap Time', 'Lap type', 
                         'Pressure FR', 'Pressure FL', 'Pressure RR', 'Pressure RL', 
                         'Temp FR', 'Temp FL', 'Temp RR', 'Temp RL',
                         'Road Temp')
lapData <- dplyr::filter(lapData, Driver == "[personal info]")
lapData <- dplyr::filter(lapData, is.na(Penalty))
lapData <- dplyr::filter(lapData, Lap > 1)

I then use print(ggplot(data = lapData, mapping = aes(Lap, 'Lap Time')) + geom_line()) to print the data, and it looks like this:
plot showing loss of precision
If it isn't clear, the vertices of the graph line are rounded to the seconds value instead of using the full milisecond precision, which I would like to have.
If I then print(lapData), I see the following entries under 'Lap Time':
printed tibble
I did some research, and found this, which seems to indicate that the loss of precision in the printout from the tibble is inconsequential, and the full data is still stored in the tibble. However, the plot contradicts this statement.

How do I get the plot to show the full millisecond resolution?

2 Answers 2

2

Your time format doesn't agree with the time format that readr expects by default. Specifically, readr interprets 1:34.434 as 1 hour and 34 minutes, rather than as 1 minute and 34.434 seconds.

text <- "id,time
1,1:23.456
2,2:34.567
3,3:45.678
"
cat(text, file = "foo.csv")

library("readr")
tt1 <- read_csv("foo.csv")
tt1
## # A tibble: 3 × 2
##      id time  
##   <dbl> <time>
## 1     1 01:23 
## 2     2 02:34 
## 3     3 03:45

as.double(tt1$time) / 60 # numbers of minutes
## [1]  83 154 225

The documentation suggests to use the col_types argument of read_csv to specify the time format. Normally, this would work:

col_types <- list(id = col_integer(), time = col_time(format = "%M:%OS"))

But it doesn't:

tt2 <- read_csv("foo.csv", col_types = col_types)
## Warning message:                                                                                                   
## One or more parsing issues, see `problems()` for details

tt2
## # A tibble: 3 × 2
##      id time  
##   <int> <time>
## 1     1    NA 
## 2     2    NA 
## 3     3    NA

The problem is that readr's parser requires minutes to be padded with zeros:

parse_time("01:23.456", format = "%M:%OS")
## 00:01:23.456

parse_time("1:23.456", format = "%M:%OS")
## Warning: 1 parsing failure.
## row col         expected   actual
##   1  -- time like %M:%OS 1:23.456
## 
## NA

That surprised me, because base R's parser doesn't have that constraint:

strptime("1:23.456", format = "%M:%OS")
## [1] "2022-02-11 00:01:23 EST"

A workaround is to read the offending column as a character vector and coerce it to numeric via strptime after:

tt3 <- read_csv("foo.csv", col_types = list(id = col_integer(), time = col_character()))
tt3
## # A tibble: 3 × 2
##      id time    
##   <int> <chr>   
## 1     1 1:23.456
## 2     2 2:34.567
## 3     3 3:45.678

library("dplyr")
tt4 <- tt3 %>% mutate(seconds = with(strptime(time, format = "%M:%OS"), 60 * min + sec))
options(pillar.sigfig = 10L)
tt4
## # A tibble: 3 × 3
##      id time     seconds
##   <int> <chr>      <dbl>
## 1     1 1:23.456  83.456
## 2     2 2:34.567 154.567
## 3     3 3:45.678 225.678

You can also do the coercion with lubridate, which has a specialized parser:

library("lubridate")
tt5 <- tt3 %>% mutate(seconds = as.double(as.duration(ms(time))))
identical(tt4, tt5)
## [1] TRUE
1
  • It seems that a leading zero is required, try parse_time("01:23.456", format = "%M:%OS"). Feb 11, 2022 at 5:10
1

To avoid readr's guessing, you could use conventional read.csv.

r <- read.csv('foo.csv')

Next, it is probably better to use pure milliseconds. For this, we may use strptime with"%M:%OS" which returns the beautiful "POSIXlt" format that we can put in a with and play with the minutes and seconds.

r$lap_time_ms <- with(strptime(r$lap_time, format="%M:%OS"), 6e4*min + 1e3*sec)

r
#   lap_time lap          x lap_time_ms
# 1 1:29.134   1  0.9292880       89134
# 2 1:26.233   2 -0.3301566       86233
# 3 1:28.033   3 -1.5426225       88033
# 4 1:26.434   4 -0.9961375       86434
# 5 1:26.634   5  1.1610645       86634
# 6 1:27.634   6 -0.2817558       87634

If you want a y-axis formatted in <secs>:<mins> format, use a sequence along the range of the lap times with steps in seconds.

at <- do.call(seq, c(as.list(range(ceiling(r$lap_time_ms/1e3))*1e3), 1e3))
sq <- at %/% 1e3 |> {\(.) paste(. %/% 60, . %% 60, sep=':')}()

plot(lap_time_ms ~ lap, r, type='l', yaxt='n')
axis(2, at=at, labels=sq)

enter image description here

This should also be possible with ggplot2 package.


Data:

dat <- read.table(header=TRUE, text='lap_time
1:29.134
1:26.233
1:28.033
1:26.434 
1:26.634
1:27.634
') |> transform(lap=1:6, x=rnorm(6))
write.csv(dat, 'foo.csv', row.names=FALSE)
5
  • 1
    Lap times aren't really time stamps, though. The most natural class in base R is difftime. But then you do lose access to axis.POSIXct ... Feb 11, 2022 at 6:25
  • 1
    @MikaelJagan You're right, it's probably better to use pure milliseconds, see my updated answer.
    – jay.sf
    Feb 11, 2022 at 7:25
  • 1
    One way to avoid string splitting: with(strptime(c("1:23.456", "2:34.567", "3:45.678"), format = "%M:%OS"), 60 * min + sec). strptime doesn't require minutes to be padded with zeros, hence my surprise at the fact that readr::parse_time does. Feb 11, 2022 at 18:21
  • 1
    @MikaelJagan This is wonderful! I never realized that strptime actually returns "POSIXlt"! I've taken that up in the answer.
    – jay.sf
    Feb 11, 2022 at 18:49
  • 1
    The more questions I answer about readr, the more I dread ever having to use it... [end rant] Feb 11, 2022 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.