Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

database - How can i pass from monthly data to quarterly data? R data.frame

Hello I got something like this

I got different CIIU (later) and different Provincias, the "Time series" is "exportaciones". (Time goes from Jan 2011 to Dec 2020, there′re 11 CIIUs for each Provincia)

As you can see it's monthly data. How can I keep this data frame structure and still manage to get the quarterly data? (Sum from Jan to March, then April to June, July to September and finally October to December)

   CIIU                                                fecha      Provincia exportaciones
   <chr>                                               <date>     <chr>             <dbl>
 1 Fabricación de ordenadores (computadoras) centrales 2011-01-01 AZUAY                 0
 2 Fabricación de ordenadores (computadoras) centrales 2011-02-01 AZUAY                 0
 3 Fabricación de ordenadores (computadoras) centrales 2011-03-01 AZUAY                 0
 4 Fabricación de ordenadores (computadoras) centrales 2011-04-01 AZUAY                 0
 5 Fabricación de ordenadores (computadoras) centrales 2011-05-01 AZUAY                 0
 6 Fabricación de ordenadores (computadoras) centrales 2011-06-01 AZUAY                 0
 7 Fabricación de ordenadores (computadoras) centrales 2011-07-01 AZUAY                 0
 8 Fabricación de ordenadores (computadoras) centrales 2011-08-01 AZUAY                 0
 9 Fabricación de ordenadores (computadoras) centrales 2011-09-01 AZUAY                 0
10 Fabricación de ordenadores (computadoras) centrales 2011-10-01 AZUAY                 0
question from:https://stackoverflow.com/questions/66053013/how-can-i-pass-from-monthly-data-to-quarterly-data-r-data-frame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since it's not clear exactly what the final output should look like, this is just pseudo-code. We use lubridate::quarter to create a grouping field with quarter and year. Then we can summarize the data to the quarter/yearly level.

library(tidyverse)
library(lubridate)

data %>% mutate(year_quarter = lubridate::quarter(fecha, with_year = TRUE)) %>%
  group_by(year_quarter, other_categories_to_summarize_by) %>%
  summarize(exportaciones = sum(exportaciones))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...