我想将我的季度数据转换为每月数据,但得到了错误:
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上已经有很多问题了,但我想try 一下,有人能帮我吗?
数据样本:
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