Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create new column with sequential numbering based on another column with two variables

I have a dataframe that looks like this:

structure(list(Date = structure(c(1630544400, 1630548000, 1630551600, 
1630555200, 1630558800, 1630562400, 1630566000, 1630569600, 1630573200, 
1630576800, 1630580400, 1630630800, 1630634400, 1630638000, 1630641600, 
1630645200, 1630648800, 1630652400, 1630656000, 1630659600), tzone = "America/Chicago", class = c("POSIXct", 
"POSIXt")), daytime = c("Night", "Night", "Night", "Night", "Morning", 
"Morning", "Morning", "Morning", "Morning", "Morning", "Morning", 
"Night", "Night", "Night", "Night", "Morning", "Morning", "Morning", 
"Morning", "Morning")), row.names = c(NA, -20L), class = c("tbl_df", 
"tbl", "data.frame"))

I would like to create another column to group the night and morning sequentially so the output would look like this:

   Date                daytime        nightcount
   <dttm>              <chr>          <dbl>
 1 2021-09-01 20:00:00 Night            1
 2 2021-09-01 21:00:00 Night            1  
 3 2021-09-01 22:00:00 Night            1
 4 2021-09-01 23:00:00 Night            1
 5 2021-09-02 00:00:00 Morning          1
 6 2021-09-02 01:00:00 Morning          1
 7 2021-09-02 02:00:00 Morning          1
 8 2021-09-02 03:00:00 Morning          1
 9 2021-09-02 04:00:00 Morning          1
10 2021-09-02 05:00:00 Morning          1
11 2021-09-02 06:00:00 Morning          1
12 2021-09-02 20:00:00 Night            2
13 2021-09-02 21:00:00 Night            2  
14 2021-09-02 22:00:00 Night            2
15 2021-09-02 23:00:00 Night            2  
16 2021-09-03 00:00:00 Morning          2
17 2021-09-03 01:00:00 Morning          2
18 2021-09-03 02:00:00 Morning          2
19 2021-09-03 03:00:00 Morning          2
20 2021-09-03 04:00:00 Morning          2

Is there an easy solution for this using dplyr?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create a logical value when "Morning" turns to "Night" and then use cumsum to sum these logical values across rows:

library(dplyr)

df |>
  mutate(nightcount = cumsum(daytime == "Night" & lag(daytime, default = "Morning") == "Morning"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading