0

Below a specific cell from my dataset:

PT23M55.39S

The cell tells me how many minutes (23 minutes) and seconds (55.39 seconds) a user has spent on a webpage.

The cell is of the property char (character).

How do I convert it to a numeric where I express the visit time in only seconds (23 * 60 + 55.39 = 1435.39 seconds)?

1 Answers1

1

Using lubridate functions ms and period_to_seconds you can do -

library(lubridate)

x <- 'PT23M55.39S'
period_to_seconds(ms(x))
#[1] 1435.39

In base R, you may use strcapture to extract the data using regex into minutes and seconds separately, multiply minutes value by 60 and add the two numbers.

strcapture('[A-Z]+(\\d+)M(\\d+\\.\\d+)', x, 
           proto = list(minutes = numeric(), seconds = numeric())) |>
  transform(duration_in_seconds = minutes * 60 + seconds)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213