r-添加日期周围的新观察值和重复值



我有多个与日期相关的观测值,希望在每个现有日期前后添加+-3天的新观测值,并复制这些天的值。

示例df:

library(lubridate)
Time <- c(as_date(17498), as_date(18498), as_date(18298))
Measurement <- c(11, 42, 28)
df <- data.frame(Time, Measurement)

目标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)

使用tidyverse(尤其是purrr(可以完成此操作。。。

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

最新更新