根据 R 中的日期列创建具有重复值的新数据框

Create new dataframe with repeated values based on Date Column in R

我有一个非常基本的问题。我有以下两列示例数据框; “日期”和“值”:

df <- structure(list(Date = structure(c(17075, 17083), class = "Date"), Value = c(0.16, 0.17)), row.names = c(NA, 2L), class = "data.frame")

我想创建一个新的数据框,其中包含特定日期前后的重复值。日期不应重复,但应根据重复值所采取的步骤数进行更改。

例如,对于上面的数据框,如果我想围绕日期重复 +-3 个步骤,则输出数据框应如下所示:

out <- structure(list(Date = structure(c(17072,17073,17074,17075,17076,17077,17078,17080,17081,17082,17083,17084,17085,17086 , class = "Date"), Value = c(0.16,0.16,0.16,0.16,0.16,0.16,0.16,0.17,0.17,0.17,0.17,0.17,0.17, 0.17)), row.names = c(NA, 14L), class = "data.frame")

我们如何完成这个任务?我尝试使用 rep 函数但对我不起作用。

如果我们有一个 n 作为 3,我们可以使用 rowwise 并在 list 中得到 'Date' 的 seq 量,然后 unnest list

library(dplyr)
library(tidyr)
library(lubridate)
n <- 3
df %>% 
  rowwise %>%
  mutate(Date =  list(seq(Date - days(n), length.out = 2 *n +1, 
        by = 'day'))) %>% 
  ungroup %>%
  unnest(c(Date))

-输出

# A tibble: 14 x 2
#   Date       Value
#   <date>     <dbl>
# 1 2016-09-28  0.16
# 2 2016-09-29  0.16
# 3 2016-09-30  0.16
# 4 2016-10-01  0.16
# 5 2016-10-02  0.16
# 6 2016-10-03  0.16
# 7 2016-10-04  0.16
# 8 2016-10-06  0.17
# 9 2016-10-07  0.17
#10 2016-10-08  0.17
#11 2016-10-09  0.17
#12 2016-10-10  0.17
#13 2016-10-11  0.17
#14 2016-10-12  0.17

map

可能会快一点
library(purrr)
df %>%
  mutate(Date = map(Date, ~ seq(.x - days(n), 
            length.out = 2 * n + 1, by = 'day'))) %>% 
  unnest(Date)

凌乱的基础 R:

n <- 3
unique_dates <- unique(df$Date)
within(
  merge(
    df, 
    do.call(
      rbind,
      lapply(
        split.default(unique_dates, seq_len(length(unique_dates))),
        function(x){
          y <- as.Date(x)
          z <- sort(c(y - seq_len(n), y, y + seq_len(n)))
          data.frame(Date = y, Dates = z)
        }
      )
    ),
    by = "Date", 
    all = TRUE
  ),
  {
    Date <- Dates
    rm(Dates)
  }
)