gpt4 book ai didi

r - 使用 R 将日期序列添加到数据框中

转载 作者:行者123 更新时间:2023-12-04 08:56:26 24 4
gpt4 key购买 nike

我有一个数据框如下:

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.

最佳答案

问题是“值”是在没有任何分组的情况下创建的。我们可以做一个 group_by并创建 seq每个“国家”内“日期”的 uence,指定 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 ,“值”可以是 rep许可的
df %>%
mutate(date = rep(values, length.out = sum(county == first(country))))

关于r - 使用 R 将日期序列添加到数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63804602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com