Reshape list in data.frame row to long format

I would like to make a line graph of lap times, but the way data were collected makes that challenging.

Lap times were stored in a single cell in Excel, delimited by commas. :face_with_diagonal_mouth:

Example data:

lap_data <- data.frame(
                id = c(1L),
              name = c("David"),
              laps = c(3L),
              lap_times = c("33,28,30"))

Which produces this:

  id  name laps lap_times
1  1 David    3  33,28,30

I would like to reshape it into something like this for ease of plotting:

  id  name lap lap_time
1  1 David   1       33
2  1 David   2       28
3  1 David   3       30

I can convert the lap time characters into a numeric list using the strapply function from the gsubfn package:

library(gsubfn)

lap_data$lap_times <- strapply(data$lap_times, "\\d+", as.numeric)

#lap_times now number list 
  id  name laps  lap_times
1  1 David    3 33, 28, 30

But I don't know how to proceed from here.

Any help would be appreciated. It's not often I'm forced to work with data this funky.

How about this?

library(dplyr)
library(tidyr)

lap_data <- data.frame(
    id = c(1L),
    name = c("David"),
    laps = c(3L),
    lap_times = c("33,28,30"))

lap_data %>% 
    separate_rows(lap_times, convert = TRUE) %>% 
    group_by(name) %>% 
    mutate(lap = row_number()) %>% 
    select(id, name, lap, lap_time = lap_times)
#> # A tibble: 3 × 4
#> # Groups:   name [1]
#>      id name    lap lap_time
#>   <int> <chr> <int>    <int>
#> 1     1 David     1       33
#> 2     1 David     2       28
#> 3     1 David     3       30

Created on 2022-06-03 by the reprex package (v2.0.1)

Thank you, @andresrcs. That solution saved me a world of trouble.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.