Consider the following data
library(lubridate)
df <- data.frame(x_seconds = c(1,2,3,4,5))
start_time <- ymd_hms("2022-01-01 13:45:00")
How do I get the vector of seconds into a vector of timestamps since the start_time
?
# A tibble: 5 x 2
x_seconds z_ts
<dbl> <dttm>
1 1 2022-01-01 13:45:01
2 2 2022-01-01 13:45:02
3 3 2022-01-01 13:45:03
4 4 2022-01-01 13:45:04
5 5 2022-01-01 13:45:05
Note that a solution should work for an (arbitrary) large vector of seconds.
CodePudding user response:
Simply
library(dplyr)
start_time <- ymd_hms("2022-01-01 13:45:00")
df %>%
mutate(z_ts = x_seconds start_time)
x_seconds z_ts
1 1 2022-01-01 13:45:01
2 2 2022-01-01 13:45:02
3 3 2022-01-01 13:45:03
4 4 2022-01-01 13:45:04
5 5 2022-01-01 13:45:05
or using base R
df$z_ts = df$x_seconds start_time
df
x_seconds z_ts
1 1 2022-01-01 13:45:01
2 2 2022-01-01 13:45:02
3 3 2022-01-01 13:45:03
4 4 2022-01-01 13:45:04
5 5 2022-01-01 13:45:05