从每年到每月的爆炸数据

问题描述 投票:0回答:1

这是一个有关以下问题:

Exploding dates from annual to monthly

我试图将数据集稍微更改为:

                 date type     bps
1 2012-06-28 16:00:00    A 2.44376
2 2012-06-28 16:00:00    B 1.73054
3 2012-06-28 16:00:00    C 1.68171
4 2013-06-27 16:00:00    A 2.07297
5 2013-06-27 16:00:00    B 1.77073

以下是数据集定义:

df = structure(list(date = structure(c(1340892000, 1340892000, 1340892000, 
                                       1372341600, 1372341600), class = c("POSIXct", "POSIXt"), tzone = ""), type = 
                      c("A", "B", "C", "A", "B"), bps = 
                      c(2.44376, 1.73054, 1.68171, 2.07297, 1.77073)), .Names = c("date", "type", 
                                                                                  "bps"), class = "data.frame", row.names = c(NA, 5L))

问题是以下代码失败:

df_tbl <- as_tibble(df)

df2_tbl <- df_tbl %>% mutate(date = ceiling_date(date, 'month'),
                             date = map2(date, 
                                         lead(date - 1, default = last(date)), 
                                         seq, by = 'month')) %>% 
  unnest() %>% 
  mutate(date = date - days(1))

出现以下错误:

Error: Problem with `mutate()` input `date`.
x wrong sign in 'by' argument
ℹ Input `date` is `map2(date, lead(date - 1, default = last(date)), seq, by = "month")`.
Run `rlang::last_error()` to see where the error occurred.

[似乎原始数据已经包含每月数据,而此数据集是年度数据。

r tidyverse lubridate
1个回答
0
投票

我认为您需要按组来应用解决方案,即type

library(tidyverse)
library(lubridate)

df_tbl %>% 
  mutate(date = ceiling_date(date, 'month')) %>%
  group_by(type) %>%
  mutate(date = map2(date, lead(date - 1, default = last(date)),seq, by = 'month')) %>% 
  unnest(date) %>% 
  mutate(date = date - days(1))
© www.soinside.com 2019 - 2024. All rights reserved.