Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate hour and minutes in R

Tags:

dataframe

r

I have a column for time, but it hasn't been separated by : or any thing. It looks like this:

  person      time
   1            356
   1            931
   1            2017
   1            2103
   2            256
   2            1031
   2            1517
   2            2206

How do I separate them?

like image 481
sherek_66 Avatar asked Jan 31 '26 06:01

sherek_66


1 Answers

There are different ways of approaching the issue. Which method you choose depends on your desired output.

For example, you could use stringr::str_split to split time into a list vector of hours and minutes using a positive look-ahead

library(tidyverse)
df %>% mutate(time = str_split(time, "(?=\\d{2}$)"))
#  person   time
#1      1  3, 56
#2      1  9, 31
#3      1 20, 17
#4      1  2, 13
#5      2  2, 56
#6      2 10, 31
#7      2 15, 17
#8      2  2, 26

Or we can use tidyr::separate to create two new columns hours and minutes

df %>% separate(time, c("hours", "minutes"), sep = "(?=\\d{2}$)")
#  person hours minutes
#1      1     3      56
#2      1     9      31
#3      1    20      17
#4      1     2      13
#5      2     2      56
#6      2    10      31
#7      2    15      17
#8      2     2      26

In response to your comment you could use stringr::str_replace

df %>% mutate(time = str_replace(time, "(?=\\d{2}$)", ":"))
#  person  time
#1      1  3:56
#2      1  9:31
#3      1 20:17
#4      1  2:13
#5      2  2:56
#6      2 10:31
#7      2 15:17
#8      2  2:26

And the same in base R using sub

transform(df, time = sub("(?=\\d{2}$)", ":", time, perl = TRUE))

giving the same result.

Sample data

df <- read.table(text = "
person      time
  1            356
  1            931
  1            2017
  1            213
  2            256
  2            1031
  2            1517
  2            226", header = T)
like image 145
Maurits Evers Avatar answered Feb 01 '26 20:02

Maurits Evers