我想将季度数据转换为月度数据,但出现错误:
Error in `mutate()`:
! Problem while computing `Month_Num = rep(rep(1:3, each = 2), 4)`.
✖ `Month_Num` must be size 8 or 1, not 24.
我知道在Stack Overflow上已经有很多问题了,但是我想尝试一下这样的东西,有人能帮忙吗?
数据样本:
new_data <- data.frame(
Year = c(2021, 2021, 2021, 2021, 2022, 2022, 2022, 2022),
Quarter = c("1st Quarter", "2nd Quarter", "3rd Quarter", "4th Quarter", "1st Quarter", "2nd Quarter", "3rd Quarter", "4th Quarter"),
Government_Expenditure = c(139.95, 132.93, 134.64, 141.10, 151.08, 140.79, 143.05, 149.32)
)
验证码:
library(tidyr)
monthly_data <- new_data %>%
mutate(Month_Num = rep(rep(1:3, each = 2), 4)) %>%
mutate(Month = case_when(Month_Num == 1 ~ "January",
Month_Num == 2 ~ "February",
Month_Num == 3 ~ "March")) %>%
select(-Month_Num) %>%
pivot_longer(cols = c("Month", "Government_Expenditure"),
names_to = c("Variable", ".value"),
names_pattern = "(.*)\\.(.*)") %>%
mutate(Month = as.numeric(Month)) %>%
pivot_wider(names_from = Month, values_from = Government_Expenditure)
monthly_data
1条答案
按热度按时间pepwfjgg1#
也许这会有所帮助-为“季度”和相应的“月份”创建一个键/值嵌套数据,与“季度”上的原始数据连接,
unnest
“月份”的tibble列,并使用pivot_wider
将其整形为“宽”格式