Create time variables

Packages: dplyr, lubridate, hms


Timestamps variables are part of the data collected in ESM studies, in particular, the ‘scheduled’, ‘sent’, ‘start’, and ‘end’ variables (see terminology). Based on them, we can create time variables that are essential for data manipulation, time series visualization, and statistical analysis. After demonstrating how to reformat time variables and introducing the lubridate package, we present multiple methods to extract time components and compute new variables from the timestamps variables:

Each time we create one of those variables, it is important to choose carefully which timestamps variable (i.e., ‘scheduled’, ‘send’, ‘start’, ‘end’) you want to base this new variable on. Often, the ‘sent’ variable makes the most sense.

Warning

These specific variables are susceptible to various problems, especially issues arising from duplications or sampling schemes (refer to step 2). It may be necessary to recalculate these variables once problems affecting their computation are identified and resolved. In addition, you should make sure that the dataframe is organized in function of participant id and timestamps variable order.

Reformat timestamps variables

Before creating time variables, we have to make sure that they are in a datetime format (e.g., POSIXct, POSIXlt), in particular, the POSIXct is often used. The ‘as.POSIXct()’ function in R is used to convert a character or numeric vector to a POSIXct class. It has several arguments, including:

  • tz: time zone (e.g., ‘Europe/Paris’, ‘UTC’, ‘GMT’). Importantly, when reformating, the default setting is your computer local timezone setting (use ‘Sys.timezone()’ or check the last letter from ‘Sys.time()’ output).
  • origin: the origin from which the date-time object is calculated. It is necessary if the input is in a numerical format (e.g., 1523264423). Typically, “1970-01-01” is used as it is the default reference point in R. Nonetheless, we should make sure to use the correct origin, otherwise, the new values will be incorrect.
  • format: if the input is a character string we must specify its format (e.g., “2021-11-25 12:13:01” would be “%Y-%m-%d %H:%M:%OS”).

When reformatting to a POSIXct format from:

  • a numerical format, you have to set the original ‘origin’ value. The resulting date will be determined by adding the value in seconds to this origin (i.e., origin + value). Importantly, this calculation is consistently performed in the GMT time zone. If an alternative timezone is specified, the function will subsequently adjust the resulting datetime to the designated timezone.
  • a character format, you might have to provide the ‘format’ argument.

data$start = as.POSIXct(data$start, origin="1970-01-01")

Whenever we have multiple datetime variables to reformat, we can use ‘mutate()’ and ‘across()’ from the dplyr package to change their format at once.

data = data %>%
    mutate(across(c(scheduled,sent,start,end), ~as.POSIXct(., format="%Y-%m-%d %H:%M:%OS")))

Whatever method you use, you need to double-check the output values. Timedate variables are very sensitive to change and are truly important for later data manipulation and statistical analysis.

Warning

Important information:

  • A good practice is to check after reformating if the datetime values has been subject to unwanted modifications.
  • When determining the time difference between datetime values associated with different timezones, the calculation takes into consideration the timezone details to provide an accurate result.
  • Specifying “CEST” (Central European Summer Time) in the tz argument does not work, even if it is indicated. Prefer using “Europe/Paris”, “Europe/Brussels”, etc.
  • If timedate is accurate but the timezone is not (e.g., “GMT”), you can employ ‘force_tz()’ to obtain a datetime with the same clock time but with the new timezone indicated.

Lubridate

One very useful package to handle dates and times is the lubridate package. It can be useful for performing common date/time-related operations, such as parsing date/time data, extracting specific components (e.g. day, month, year) from a date/time object, and performing arithmetic on date/time values. You can easily find an introductory tutorial online (link).

library(lubridate)

Some functions of this package need to be informed of which day is the start of the week. It is particularly important whenever you need to extract the week number of a day. By default, the start of the week is set as Sunday, following the American calendar. You can modify it knowing that this option follows ISO conventions: 1 means Monday (as in Europe) and 7 means Sunday (as in the USA). If you want the start of the week to be Monday (=1), you can set up:

  • the global variable.
  • argument of the lubridate functions that are impacted, such as the ‘wday()’ function.

options("lubridate.week.start" = 1)

Extract date and time elements

Extract datetime components (e.g., day, month, hour) by creating one variable per relevant element:

library(lubridate)
data$year = year(data$sent)             # Extract year
data$month = month(data$sent)           # Extract month number
data$day = day(data$sent)               # Extract day
data$hour = hour(data$sent)             # Extract hour
data$minute = minute(data$sent)         # Extract minute
data$second = second(data$sent)         # Extract second
data$wday = lubridate::wday(data$sent)  # Extract day of the week number

It returns:

  id                sent year month day hour minute second wday
1  1 2018-10-17 08:00:11 2018    10  17    8      0     11    3
2  1 2018-10-17 09:00:22 2018    10  17    9      0     22    3
3  1 2018-10-17 10:00:08 2018    10  17   10      0      8    3
4  1 2018-10-17 10:59:52 2018    10  17   10     59     52    3
5  1 2018-10-17 12:00:15 2018    10  17   12      0     15    3
6  1 2018-10-18 08:00:08 2018    10  18    8      0      8    4

Note that the ‘wday()’ (i.e., day of the week) function returns, by default, number starting from 1 (i.e., Sunday) to 7 (i.e., Saturday). If you want Monday to be defined as the first day of the week see above the lubridate section.

Observation number

Create a variable that indicates the serial order of the beeps for each participant. Be careful when computing ‘obsno’. Make sure that there are no duplicated rows, that the dataframe is well ordered based on id and timestamps (e.g., sent time), and that those variables don’t have any missing values or other issues.

Warning

Given the crucial role of this variable in data management and statistical models, we strongly advise verifying that the computation concludes without encountering any issues.

data = data[order(data$id, data$sent), ] # Order the dataframe
data$obsno = ave(rep(1, nrow(data)), data$id, FUN = seq_along)

It returns:

  dyad id                sent obsno
1    1  1 2018-10-17 08:00:11     1
2    1  1 2018-10-17 09:00:22     2
3    1  1 2018-10-17 10:00:08     3
4    1  1 2018-10-17 10:59:52     4
5    1  1 2018-10-17 12:00:15     5
6    1  1 2018-10-18 08:00:08     6

Beep number in a day

Compute the beep number for observation of each day of each participant. The first beep of the day will be set as 1, the second beep as 2, etc. To create this variable, we need to first compute the ‘daycum’ variable (see below). We propose two methods:

  • The first method is straightforward but requires certainty that no beeps are missing in the dataset. It assigns a beep number to each observation based on its order within each day.

data = data[order(data$id, data$sent), ]
data$beepno = ave(rep(1, nrow(data)), data$id, data$daycum, FUN = seq_along)

It returns:

  dyad id                sent daycum beepno
1    1  1 2018-10-17 08:00:11 1 days      1
2    1  1 2018-10-17 09:00:22 1 days      2
3    1  1 2018-10-17 10:00:08 1 days      3
4    1  1 2018-10-17 10:59:52 1 days      4
5    1  1 2018-10-17 12:00:15 1 days      5
6    1  1 2018-10-18 08:00:08 2 days      1
  • The second method is more flexible. It assigns the beep number in the function of pre-defined sent hours (implemented using ‘sched_sent’). A tolerance margin in minutes is set using the variable ‘interval_sent’. Indeed, the servers that handle the sending of the beeps can be delayed for multiple reasons. Check the outputs carefully, in particular check missing values in beepno and duplicated beepno numbers within the same day. If an observation has no values assigned, it is likely because it was sent (or started) outside of the predefined interval.
# Timestamps of sampling scheme
sched_sent = hms::as_hms(c("09:59:00", "10:59:00", "11:59:00", "12:59:00", "13:59:00"))   # Original pre-defined hours that the beep should have been sent
interval_sent = 11 # Interval of time in min
sched_int_sent = hms::as_hms(sched_sent + interval_sent * 60) # 11 min = 11*60 sec

# Assign beepno
data[,"beepno"] = NA
for (row in 1:nrow(data)){
    sent_ = hms::as_hms(data$sent[row])
    beepno = which(sent_ > sched_sent & sent_ < sched_int_sent)
    if (length(beepno) != 1) beepno = NA
    data[row,"beepno"] = beepno
}

It returns:

  dyad id                sent daycum beepno
1    1  1 2018-10-17 08:00:11 1 days     NA
2    1  1 2018-10-17 09:00:22 1 days     NA
3    1  1 2018-10-17 10:00:08 1 days      1
4    1  1 2018-10-17 10:59:52 1 days      2
5    1  1 2018-10-17 12:00:15 1 days      3
6    1  1 2018-10-18 08:00:08 2 days     NA
Warning

Given the crucial role of this variable in data management and statistical models, we strongly advise verifying that the computation concludes without encountering any issues.

Cumulative day

Compute the cumulative number of days:

  • since the first day of the participant in the study (‘daycum’).
  • since the first day of the dyad (whatever which partner started first) in the study (‘daycum_dyad’). The only modification is the grouping variable used (i.e., ‘dyad’). Note that this variable might be important to create a dyadic format of the dataframe.

data = data %>% 
    group_by(id) %>%
    mutate(daycum = difftime(lubridate::date(sent), lubridate::date(min(sent, na.rm=TRUE)), units="days") + 1)

It returns:

  dyad id                sent daycum daycum_dyad
1    1  1 2018-10-17 08:00:11 1 days      1 days
2    1  1 2018-10-17 09:00:22 1 days      1 days
3    1  1 2018-10-17 10:00:08 1 days      1 days
4    1  1 2018-10-17 10:59:52 1 days      1 days
5    1  1 2018-10-17 12:00:15 1 days      1 days
6    1  1 2018-10-18 08:00:08 2 days      2 days
Note

When determining the time difference between datetime values associated with different timezones, the calculation takes into consideration the timezone details to provide an accurate result.

Cumulative weeks

Compute the week number for each observation of a participant since the start of its participation. In the script you can see ‘+1’. It is to ensure that the first week is specified as 1 and not 0.

Warning

The ‘weekcum’ variable depends on the ‘lubridate.week.start’ option, which defines the first day of the week (e.g., Monday, Sunday). Make sure to set this option before computing the ‘weekcum’ variable. See the lubridate section for more information.

data = data %>% 
    group_by(id) %>%
    mutate(min_week = floor_date(min(sent, na.rm=TRUE), unit="weeks"), 
           weekcum = ceiling(difftime(floor_date(sent, unit="weeks"), min_week, units="weeks")) + 1)

It returns:

  dyad id                sent weekcum
1    1  1 2018-10-17 08:00:11 1 weeks
2    1  1 2018-10-17 09:00:22 1 weeks
3    1  1 2018-10-17 10:00:08 1 weeks
4    1  1 2018-10-17 10:59:52 1 weeks
5    1  1 2018-10-17 12:00:15 1 weeks
6    1  1 2018-10-18 08:00:08 1 weeks

Duration in days

Compute the duration (in days) of the study for each participant. In other words, compute the difference in days between the first beep and the last beep within each participant.

data = data %>%
    group_by(id) %>%
    mutate(duration = difftime(lubridate::date(max(sent, na.rm=TRUE)), lubridate::date(min(sent, na.rm=TRUE)), units="days") + 1)

It returns:

  dyad id                sent duration
1    1  1 2018-10-17 08:00:11  14 days
2    1  1 2018-10-17 09:00:22  14 days
3    1  1 2018-10-17 10:00:08  14 days
4    1  1 2018-10-17 10:59:52  14 days
5    1  1 2018-10-17 12:00:15  14 days
6    1  1 2018-10-18 08:00:08  14 days

Day number in study

Compute for each observation the day number since the start of the study (over all participants).

data = data %>% 
    mutate(day1_study = lubridate::date(min(sent, na.rm=TRUE)),
           daynr_study = difftime(lubridate::date(sent), day1_study, units="days") + 1)

It returns:

  dyad id                sent daynr_study
1    1  1 2018-10-17 08:00:11      1 days
2    1  1 2018-10-17 09:00:22      1 days
3    1  1 2018-10-17 10:00:08      1 days
4    1  1 2018-10-17 10:59:52      1 days
5    1  1 2018-10-17 12:00:15      1 days
6    1  1 2018-10-18 08:00:08      2 days

Beep time since midnight

Compute for each observation the delay in minutes since the start of the day (since midnight).

data$beeptime = difftime(data$sent, lubridate::date(data$sent), units="mins")

It returns:

  dyad id                sent      beeptime
1    1  1 2018-10-17 08:00:11 480.1833 mins
2    1  1 2018-10-17 09:00:22 540.3667 mins
3    1  1 2018-10-17 10:00:08 600.1333 mins
4    1  1 2018-10-17 10:59:52 659.8667 mins
5    1  1 2018-10-17 12:00:15 720.2500 mins
6    1  1 2018-10-18 08:00:08 480.1333 mins

Continuous time

Compute for each observation a variable that indicates the time lag since the first measurement occasion for each participant. You must choose a unit such as minute or hour (full list is “auto”, “secs”, “mins”, “hours”, “days”, “weeks”) and a time interval such as 30 minutes or 2 hours.

unit = "mins"
interval_unit = 30

data = data %>% group_by(id) %>%
    mutate(start_datetime = min(start, na.rm=TRUE)) %>% ungroup() %>%
    mutate(continuoustime = as.numeric(difftime(start, start_datetime, units=unit)))

It returns:

   dyad id               start continuoustime
1     1  1                <NA>             NA
2     1  1                <NA>             NA
3     1  1                <NA>             NA
4     1  1 2018-10-17 11:00:12          0.000
5     1  1                <NA>             NA
6     1  1                <NA>             NA
7     1  1 2018-10-18 09:00:02       1319.833
8     1  1 2018-10-18 10:00:41       1380.483
9     1  1 2018-10-18 11:00:30       1440.300
10    1  1                <NA>             NA


When we have dyads, we might want to take as starting time the first beep over the two dyad’s members.

unit = "mins"
interval_unit = 30

data = data %>% group_by(dyad) %>%
    mutate(start_dyad = min(start, na.rm=TRUE)) %>% ungroup() %>%
    mutate(continuoustime_dyad = as.numeric(difftime(start, start_dyad, units=unit)) / interval_unit)

It returns:

   dyad id               start continuoustime_dyad
1     1  1                <NA>                  NA
2     1  1                <NA>                  NA
3     1  1                <NA>                  NA
4     1  1 2018-10-17 11:00:12             5.99500
5     1  1                <NA>                  NA
6     1  1                <NA>                  NA
7     1  1 2018-10-18 09:00:02            49.98944
8     1  1 2018-10-18 10:00:41            52.01111
9     1  1 2018-10-18 11:00:30            54.00500
10    1  1                <NA>                  NA

Period of the day

The ‘period’ variable assigns the period of the day (e.g., morning, afternoon, evening) to each beep.

library(hms)
data$period = case_when(as_hms(data$sent) < as_hms("12:00:00") ~ "morning",
                        as_hms(data$sent) < as_hms("17:00:00") ~ "afternoon",
                        as_hms(data$sent) < as_hms("24:00:00") ~ "evening")

It returns:

  dyad id                sent    period
1    1  1 2018-10-17 08:00:11   morning
2    1  1 2018-10-17 09:00:22   morning
3    1  1 2018-10-17 10:00:08   morning
4    1  1 2018-10-17 10:59:52   morning
5    1  1 2018-10-17 12:00:15 afternoon
6    1  1 2018-10-18 08:00:08   morning

First and last beep of the Day

Whenever we have computed ‘beepno’ variable, it is easy to create a dummy variable that indicates the first observation and the last observation of the day. It requieres the computation of the ‘daycum’ variable.

data = data %>% 
  group_by(id, daycum) %>%
  mutate(first_beep = as.numeric(beepno==1),
         last_beep = as.numeric(beepno == max(beepno, na.rm=TRUE)))

It returns:

  dyad id                sent beepno first_beep last_beep
1    1  1 2018-10-17 08:00:11      1          1         0
2    1  1 2018-10-17 09:00:22      2          0         0
3    1  1 2018-10-17 10:00:08      3          0         0
4    1  1 2018-10-17 10:59:52      4          0         0
5    1  1 2018-10-17 12:00:15      5          0         1
6    1  1 2018-10-18 08:00:08      1          1         0

Weekday vs. weekend day

The ‘weekday’ variable indicates if the observation has been performed during a weekday or a weekend day. Note that we indicate with the ‘week_start’ argument that we want the week count to commence on Monday (see lubridate section).

data = data %>% 
    mutate(weekday = ifelse(wday(sent, week_start=1) %in% c(6,7), "weekend", "weekday"))

It returns:

  dyad id                sent weekday
1    1  1 2018-10-17 08:00:11 weekday
2    1  1 2018-10-17 09:00:22 weekday
3    1  1 2018-10-17 10:00:08 weekday
4    1  1 2018-10-17 10:59:52 weekday
5    1  1 2018-10-17 12:00:15 weekday
6    1  1 2018-10-18 08:00:08 weekday