Reputation: 91
I have multiple observations associated with dates and want to add new observations for +-3 days around each existing date and copy the values for those days.
Example df:
library(lubridate)
Time <- c(as_date(17498), as_date(18498), as_date(18298))
Measurement <- c(11, 42, 28)
df <- data.frame(Time, Measurement)
Aimed df:
Time_edt <- c(as_date(17495),as_date(17496),as_date(17497),as_date(17498),as_date(17499),as_date(17500),as_date(17501),
as_date(18495),as_date(18496),as_date(18497),as_date(18498),as_date(18499),as_date(18500),as_date(18501),
as_date(18295),as_date(18296),as_date(18297),as_date(18298),as_date(18299),as_date(18300),as_date(1830))
Measurement_edt <- c(11,11,11,11,11,11,11,
42,42,42,42,42,42,42,
28,28,28,28,28,28,28)
df_edt <- data.frame(Time_edt, Measurement_edt)
Upvotes: 0
Views: 34
Reputation: 18425
Using the tidyverse
(especially purrr
) you can do this...
map_df(seq_len(nrow(df)), #run through the rows. map_df outputs a dataframe
~tibble(Time = seq(df$Time[.]-3, #construct df for that row
df$Time[.]+3, 1),
Measurement = df$Measurement[.]))
# A tibble: 21 x 2
Time Measurement
<date> <dbl>
1 2017-11-25 11
2 2017-11-26 11
3 2017-11-27 11
4 2017-11-28 11
5 2017-11-29 11
6 2017-11-30 11
7 2017-12-01 11
8 2020-08-21 42
9 2020-08-22 42
10 2020-08-23 42
# ... with 11 more rows
Upvotes: 1