Home > Software engineering >  R sequence of datetimes using a known starting point and the number of rows as an endpoint
R sequence of datetimes using a known starting point and the number of rows as an endpoint

Time:08-31

Assume we have a dataframe with a specific number of rows:

df <- data.frame(points = 1:5)

and a known starting point:

library(lubridate)
start <- ymd_hms("2022-08-29 12:00:00")

All sequence commands (e.g., `seq.Date') that I can find will only take start and end values as arguments, meaning you have to know an "end" time.

So how can we create a column in df containing a sequence of datetimes where 30 seconds are added to each consecutive row, while specifying nrow(df) as the "end" argument? The reason for asking is because i would like to apply this type of operation while looping over many (much larger) dataframes.

The desired output would be:

>df

1 2022-08-29 12:00:00
2 2022-08-29 12:00:30
3 2022-08-29 12:01:00
4 2022-08-29 12:01:30
5 2022-08-29 12:02:00

CodePudding user response:

We can use

library(dplyr)
df <- df %>%
     mutate(dates = start   (points-1) * 30)

-output

> df
  points               dates
1      1 2022-08-29 12:00:00
2      2 2022-08-29 12:00:30
3      3 2022-08-29 12:01:00
4      4 2022-08-29 12:01:30
5      5 2022-08-29 12:02:00

Or use seq with length.out

df %>%
     mutate(dates = seq(start, length.out = n(), by = '30 sec'))
points               dates
1      1 2022-08-29 12:00:00
2      2 2022-08-29 12:00:30
3      3 2022-08-29 12:01:00
4      4 2022-08-29 12:01:30
5      5 2022-08-29 12:02:00
  • Related