Creating new rows conditionally

Afternoon,

Bit of an odd one, but is this possible in R Studio?

I have a dataframe that looks like this

DF <- tibble::tribble(
  ~Location,        ~Start.Time,          ~End.Time, ~Split.Shift,
   "Area 1", "22/01/2021 06:00", "22/01/2021 13:00",         "No",
   "Area 2", "23/01/2021 12:00", "23/01/2021 22:00",         "No",
   "Area 1", "24/01/2021 21:00", "25/01/2021 06:00",        "Yes"
  )

What I would like to see is that when Split.Shift = "Yes", to split the last 2 hours off the shift, create a new row and change the location? Desired output:

tibble::tribble(
  ~Location,        ~Start.Time,          ~End.Time, ~Split.Shift,
   "Area 1", "22/01/2021 06:00", "22/01/2021 13:00",         "No",
   "Area 2", "23/01/2021 12:00", "23/01/2021 22:00",         "No",
   "Area 1", "24/01/2021 21:00", "25/01/2021 04:00",        "Yes",
   "Area 2", "25/01/2021 04:00", "25/01/2021 06:00",        "Yes"
  )

Any suggestions would be massively appreciated!

Thank you,

1 Like

This could be written more compactly but it gets the answer.

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
DF <- tibble::tribble(
  ~Location,        ~Start.Time,          ~End.Time, ~Split.Shift,
  "Area 1", "22/01/2021 06:00", "22/01/2021 13:00",         "No",
  "Area 2", "23/01/2021 12:00", "23/01/2021 22:00",         "No",
  "Area 1", "24/01/2021 21:00", "25/01/2021 06:00",        "Yes"
)
DF <- DF |> mutate(across(.cols = ends_with("Time"), .fns = dmy_hm))
NotSplit <- DF |> filter(Split.Shift == "No")
Split <-  DF |> filter(Split.Shift == "Yes")
Split <- Split |> mutate(End.Time = End.Time - 7200)
NewSplit <- Split |> mutate(Start.Time = End.Time,
                            End.Time = Start.Time + 7200,
                            Location = ifelse(Location == "Area 1", "Area 2", "Area 1"))
DF <- bind_rows(NotSplit, Split, NewSplit) |> arrange(Start.Time)
DF
#> # A tibble: 4 x 4
#>   Location Start.Time          End.Time            Split.Shift
#>   <chr>    <dttm>              <dttm>              <chr>      
#> 1 Area 1   2021-01-22 06:00:00 2021-01-22 13:00:00 No         
#> 2 Area 2   2021-01-23 12:00:00 2021-01-23 22:00:00 No         
#> 3 Area 1   2021-01-24 21:00:00 2021-01-25 04:00:00 Yes        
#> 4 Area 2   2021-01-25 04:00:00 2021-01-25 06:00:00 Yes

Created on 2022-01-08 by the reprex package (v2.0.1)

2 Likes

Simple.... but rather effective!!!

Thank you !

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.