【问题标题】:add sequence of date into dataframe using R使用 R 将日期序列添加到数据框中
【发布时间】:2020-09-09 04:08:45
【问题描述】:

我有一个数据框如下:

country   day     value

AE        1        23
AE        2        30
AE        3        21
AE        4        3
BD        1        2
BD        2        23
...       ..       ..
BD        22       23

我想从 2020-08-01 到 2020-08-21 的开始日期将日期列填充到我的数据框中 对于每个组。 这是我的尝试:

values = seq(from = as.Date("2020-08-01"), to = as.Date("2020-08-21"), by = 'day')
df<- df %>% group_by(country) %>% mutate(date=values)

但它没有给我正确的结果。

这是我想要的结果:

国家起息日

AE        1        23      2020-08-01
AE        2        30      2020-08-02
AE        3        21      2020-08-03
AE        4        3       2020-08-04
BD        1        2       2020-08-01
BD        2        23      2020-08-02
...       ..       ..
BD        21       23      2020-08-21

请告诉我如何解决这个问题。 这是错误:

Error: Problem with `mutate()` input `date`.
x Input `date` can't be recycled to size 23.
ℹ Input `date` is `seq(...)`.
ℹ Input `date` must be size 23 or 1, not 23.
ℹ The error occured in group 22: country = "CU".
Run `rlang::last_error()` to see where the error occurred.

【问题讨论】:

    标签: r dataframe


    【解决方案1】:

    问题是“值”是在没有任何分组的情况下创建的。我们可以做一个group_by 并在每个“国家”内创建“日期”的sequence,指定length.out

    library(dplyr)
    df %>%
        group_by(country) %>%
        mutate(date=seq(from = as.Date("2020-08-01"), length.out = n(), 
              by = 'day'))
    

    在大型数据集中,不同的“国家”可能具有不同的频率数量。因此,最好使用length.out 而不是to 选项


    如果'country'长度都一样,和'values'长度一样,我们不需要创建group_by,'values'可以是replicated

    df %>%
        mutate(date = rep(values, length.out = sum(county == first(country))))
    

    【讨论】:

      猜你喜欢
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 2013-04-29
      • 2021-02-01
      • 2022-10-24
      • 2017-02-06
      相关资源
      最近更新 更多