Hussain Rahiminejad
Hussain Rahiminejad

Reputation: 29

Cut times into groups

Let's say I have a very big dataframe that looks like this:

Row   Time
1     01:15:12
2     09:18:22
3     21:56:01
4     13:33:23
5     11:59:56
6     17:08:38
7     21:55:16

etc.

And I know that a time between 00:00-08:00 is shift 1, a time between 08:00-16:00 is shift 2 and a time between 16:00-00:00 is shift 3. How can I make a fast working code that transforms the time values into shift 1,2 and 3?

Something like this:

Row   Time      Shift
1     01:15:12  1
2     09:18:22  2
3     21:56:01  3
4     13:33:23  2
5     11:59:56  2
6     17:08:38  3
7     21:55:16  3

I already tried to make something with Dirk's answer in this question but the times werent transformed correctly (sometimes 01:15:12 changed to 22:00:00 and sometimes to 10:00:00)

Also I don't really like nested statements since they work pretty slow on big dataframes.

Upvotes: 2

Views: 133

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50668

We can use cut:

library(tidyverse);
df %>%
    mutate(
        Time = as.POSIXct(Time, format = "%H:%M:%S"),
        Shift = cut(
            Time,
            breaks = as.POSIXct(c("00:00", "08:00", "16:00", "24:00"), format = "%H:%M"),
            labels = c("1", "2", "3")))
#  Row                Time Shift
#1   1 2018-04-19 01:15:12     1
#2   2 2018-04-19 09:18:22     2
#3   3 2018-04-19 21:56:01     3
#4   4 2018-04-19 13:33:23     2
#5   5 2018-04-19 11:59:56     2
#6   6 2018-04-19 17:08:38     3
#7   7 2018-04-19 21:55:16     3

Note this is based on your revised data.


Sample data

df <- read.table(text =
    "Row   Time
1     01:15:12
2     09:18:22
3     21:56:01
4     13:33:23
5     11:59:56
6     17:08:38
7     21:55:16", header = T)

Upvotes: 1

Related Questions