Search code examples
rdata-transform

Data transformation from Quarterly to Monthly in R


I want to convert my quarterly data to monthly but getting the error:

 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.

I know there are many questions already on Stack Overflow but I want to try something like this, can anyone help?

Data sample:

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)
)

Code:

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

Solution

  • Perhaps this helps - create a key/value nested data for the 'Quarter' and the corresponding 'Month's , join with the original data on 'Quarter', unnest the tibble column of 'Month' and reshape to 'wide' format with pivot_wider

    library(dplyr)
    library(tidyr)
    tibble(Month = month.name) %>%
      mutate(Quarter = rep(c("1st Quarter", "2nd Quarter", "3rd Quarter", 
        "4th Quarter"), each = 3)) %>%
      nest(data = Month) %>% 
      left_join(new_data, .) %>% 
      unnest(data) %>%
      pivot_wider(names_from = Month, values_from = Government_Expenditure)