mardi 22 septembre 2020

How can I label time series data by unique nights?

I want to split a time series data set (only including nighttime data already!) in separate nights to apply a missing value imputation method for every night separately. That's why I need to create a new variable "night", labelling every night separately.

Any ideas how to correctly create the variable "night" by applying the dplyr::if_else()- function (e.g., by using the "day" or "time" variable in the if conditions)?

This is the SAMPLE DATA:

# Sample Data
timestamp <- c("2020-05-26 04:15:33","2020-05-26 06:15:33","2020-05-26 22:15:33", "2020-05-26 23:15:33", "2020-05-27 00:15:33", "2020-05-27 04:15:33", "2020-05-27 22:15:33","2020-05-28 00:15:33", "2020-05-28 04:15:33", "2020-05-28 22:15:33", "2020-05-29 00:15:33")
time <- c("04:15:33","06:15:33","22:15:33", "23:15:33", "00:15:33", "04:15:33", "22:15:33","00:15:33", "04:15:33", "22:15:33", "00:15:33")
day <- c(1,1,1,1,2,2,2,3,3,3,4)
df <- as.data.frame(cbind(timestamp, time, day))
 
df
#              timestamp     time day  
# 1  2020-05-26 04:15:33 04:15:33   1 
# 2  2020-05-26 06:15:33 06:15:33   1 
# 3  2020-05-26 22:15:33 22:15:33   1 
# 4  2020-05-26 23:15:33 23:15:33   1 
# 5  2020-05-27 00:15:33 00:15:33   2 
# 6  2020-05-27 04:15:33 04:15:33   2 
# 7  2020-05-27 22:15:33 22:15:33   2 
# 8  2020-05-28 00:15:33 00:15:33   3 
# 9  2020-05-28 04:15:33 04:15:33   3 
# 10 2020-05-28 22:15:33 22:15:33   3 
# 11 2020-05-29 00:15:33 00:15:33   4 

This would be the CORRECT RESULT:

# Sample Data - CORRECT RESULT
   
    df_result
    #              timestamp     time day  night
    # 1  2020-05-26 04:15:33 04:15:33   1 night0
    # 2  2020-05-26 06:15:33 06:15:33   1 night0
    # 3  2020-05-26 22:15:33 22:15:33   1 night1
    # 4  2020-05-26 23:15:33 23:15:33   1 night1
    # 5  2020-05-27 00:15:33 00:15:33   2 night1
    # 6  2020-05-27 04:15:33 04:15:33   2 night1
    # 7  2020-05-27 22:15:33 22:15:33   2 night2
    # 8  2020-05-28 00:15:33 00:15:33   3 night2
    # 9  2020-05-28 04:15:33 04:15:33   3 night2
    # 10 2020-05-28 22:15:33 22:15:33   3 night3
    # 11 2020-05-29 00:15:33 00:15:33   4 night3

Aucun commentaire:

Enregistrer un commentaire