Skip to content
Snippets Groups Projects
Commit a57ae679 authored by mael.theuliere's avatar mael.theuliere
Browse files

initial commit :rocket:

parent 1fc8ce70
No related branches found
No related tags found
No related merge requests found
Showing
with 1652 additions and 0 deletions
^propre\.ecln\.Rproj$
^\.Rproj\.user$
^devstuff\.R$
^data-raw$
^extdata$
^LICENSE\.md$
.Rproj.user
.Rhistory
.RData
.Ruserdata
extdata/
data/
Package: propre.ecln
Title: What the Package Does (One Line, Title Case)
Version: 0.0.0.9000
Authors@R:
person(given = "Maël",
family = "THEULIERE",
role = c("aut", "cre"),
email = "mael.theuliere@gmail.com",
comment = c(ORCID = "0000-0002-5146-699X"))
Description: What the package does (one paragraph).
License: GPL (>= 3)
Encoding: UTF-8
LazyData: true
Roxygen: list(markdown = TRUE)
RoxygenNote: 7.1.1
Imports:
COGiter,
dplyr,
lubridate,
stringr,
forcats,
ggforce,
ggplot2,
glue,
gouvdown,
scales,
magrittr,
rlang,
kableExtra,
knitr,
tidyr
Remotes:
MaelTheuliere/COGiter
Depends:
R (>= 2.10)
This diff is collapsed.
# Generated by roxygen2: do not edit by hand
export("%>%")
export(FormatCaractere)
export(FormatDate)
export(creer_graphique_evolution_annuelle)
export(data_prep)
export(graphique_evolution_trim)
export(graphique_investissement_locatif)
export(graphique_series_temporelles)
export(graphique_series_temporelles_prix)
export(tableau_synthese_annuel)
export(tableau_synthese_trimestrielle)
importFrom(COGiter,filtrer_cog)
importFrom(dplyr,arrange)
importFrom(dplyr,bind_rows)
importFrom(dplyr,case_when)
importFrom(dplyr,distinct)
importFrom(dplyr,filter)
importFrom(dplyr,full_join)
importFrom(dplyr,mutate)
importFrom(dplyr,pull)
importFrom(dplyr,select)
importFrom(forcats,fct_drop)
importFrom(forcats,fct_inorder)
importFrom(forcats,fct_recode)
importFrom(forcats,fct_relevel)
importFrom(ggforce,geom_mark_circle)
importFrom(ggplot2,aes)
importFrom(ggplot2,coord_flip)
importFrom(ggplot2,facet_wrap)
importFrom(ggplot2,geom_area)
importFrom(ggplot2,geom_bar)
importFrom(ggplot2,geom_label)
importFrom(ggplot2,geom_line)
importFrom(ggplot2,geom_point)
importFrom(ggplot2,ggplot)
importFrom(ggplot2,guides)
importFrom(ggplot2,labs)
importFrom(ggplot2,margin)
importFrom(ggplot2,position_dodge)
importFrom(ggplot2,scale_x_date)
importFrom(ggplot2,scale_y_continuous)
importFrom(ggplot2,theme)
importFrom(glue,glue)
importFrom(gouvdown,gouv_colors)
importFrom(gouvdown,scale_color_gouv_discrete)
importFrom(gouvdown,scale_fill_gouv_discrete)
importFrom(grid,unit)
importFrom(kableExtra,add_header_above)
importFrom(kableExtra,add_indent)
importFrom(kableExtra,kable_styling)
importFrom(kableExtra,row_spec)
importFrom(knitr,kable)
importFrom(lubridate,"%m-%")
importFrom(lubridate,`%m+%`)
importFrom(lubridate,days)
importFrom(lubridate,month)
importFrom(lubridate,quarter)
importFrom(lubridate,year)
importFrom(lubridate,years)
importFrom(lubridate,ymd)
importFrom(magrittr,"%>%")
importFrom(rlang,.data)
importFrom(scales,dollar_format)
importFrom(scales,format_format)
importFrom(stringr,str_c)
importFrom(stringr,str_replace)
importFrom(stringr,str_split_fixed)
importFrom(tidyr,spread)
#' Conversion d'une date au mois ou trimestre en format date au jour.
#'
#' @param Periode caractère une date en format anneetrimestre ou anneemois
#' @param Periodicite caractère Trim si la date est en trimestre, Mois pour une date au mois
#' @param sep le séparateur entre l'année et le mois/trimestre
#'
#' @return une date au format date
#' @importFrom dplyr case_when
#' @importFrom lubridate ymd days `%m+%`
#' @importFrom stringr str_split_fixed str_c str_replace
#' @export
#'
#' @examples
#' FormatDate("2010-10", Periodicite = "Mois")
#' @importFrom dplyr case_when
#' @importFrom lubridate ymd days
#' @importFrom stringr str_split_fixed str_c str_replace
FormatDate<-function(Periode,Periodicite,sep="-") {
Periode1=stringr::str_split_fixed(Periode,sep,2)[,1]
Periode2=stringr::str_split_fixed(Periode,sep,2)[,2]
if (Periodicite=="Trim") {
return(
lubridate::ymd(dplyr::case_when(
Periode2 %in% c("Q1","T1","1") ~ stringr::str_c(Periode1,"0331"),
Periode2 %in% c("Q2","T2","2") ~ stringr::str_c(Periode1,"0630"),
Periode2 %in% c("Q3","T3","3") ~ stringr::str_c(Periode1,"0930"),
Periode2 %in% c("Q4","T4","4") ~ stringr::str_c(Periode1,"1231")
)
))
}
if (Periodicite=="Mois") {
return(
lubridate::ymd(stringr::str_c(stringr::str_replace(Periode,sep,""),"01")) %m+% months(1) %m+% lubridate::days(-1)
)
}
}
#' conversion d'une variable date en nommage trimestriel
#'
#' @param Periode date à convertire
#'
#' @return une chaine de caractère
#' @importFrom dplyr case_when
#' @importFrom lubridate year month
#' @export
#'
#' @examples
#' FormatCaractere("2010-10-01")
FormatCaractere<-function(Periode) {
trim<- dplyr::case_when(
lubridate::month(Periode) <=3 ~ "T1",
lubridate::month(Periode) <=6 ~ "T2",
lubridate::month(Periode) <=9 ~ "T3",
lubridate::month(Periode) <=12 ~ "T4"
)
return(
paste0(lubridate::year(Periode),trim)
)
}
#' graphique barre sur un an
#'
#' @param data Le dataframe.
#' @param type_logement Collectifs ou individuels.
#' @param type_zone Liste des types de zonage à intégrer dans la facette.
#' @param titre Le titre du graphique.
#' @param bas_de_page Le bas de page du graphique.
#'
#' @return Un graphique ggplot2.
#' @importFrom dplyr filter mutate arrange
#' @importFrom ggplot2 ggplot aes geom_bar coord_flip geom_label facet_wrap scale_y_continuous labs position_dodge
#' @importFrom scales format_format
#' @importFrom lubridate %m-%
#' @export
creer_graphique_evolution_annuelle<-function(data = indic_ecln,
type_zone = c("R\u00e9gions","D\u00e9partements"),
type_logement = "collectif",
titre="",
bas_de_page=""){
indic<-c("Encours - Appartements",
"Mises en vente - Appartements",
"Ventes - Appartements")
if (type_logement=="individuel") {
indic<- c("Encours - Maisons",
"Mises en vente - Maisons",
"Ventes - Maisons")
}
df <- data %>%
dplyr::filter(.data$Indicateur %in% indic,
.data$TypeZone %in% type_zone,
.data$TypeIndicateur=="Cumul annuel",
.data$Periode==max(.data$Periode)|.data$Periode==max(.data$Periode) %m-% years(1)) %>%
dplyr::mutate(Periode=FormatCaractere(.data$Periode),
Indicateur=str_split_fixed(.data$Indicateur," - ",2)[,1]) %>%
dplyr::arrange(.data$Zone)
ggplot2::ggplot(data = df, ggplot2::aes(x=.data$Periode,weight=.data$Valeur,fill=.data$Indicateur)) +
ggplot2::geom_bar(position=ggplot2::position_dodge())+
ggplot2::coord_flip()+
ggplot2::geom_label(data=df,
ggplot2::aes(label=format(round(.data$Valeur),big.mark = " "),
x=.data$Periode,
y=.data$Valeur,
group=.data$Indicateur),
position=position_dodge(0.9),
color="white",
fill="grey",
alpha=.2,
fontface="bold",
hjust=1.2
)+
ggplot2::facet_wrap(~.data$Zone,scales="free",ncol=4)+
ggplot2::scale_y_continuous(labels=scales::format_format(big.mark=" "))+
ggplot2::labs(title=titre,subtitle="R\u00e9alis\u00e9es sur les 12 derniers mois",x="Trimestre",y="",
caption=bas_de_page,fill="")
}
#' datapreparation des données
#'
#' @param reg code region
#' @param abc TRUE si on veut garder les zonages abc
#' @param zone_a_secretiser listes des zonages à secretiser
#' @param marches_a_secretiser liste des marchés à secretiser : individuel, collectif, tous
#'
#' @importFrom COGiter filtrer_cog
#' @importFrom dplyr filter mutate arrange bind_rows
#' @importFrom forcats fct_relevel fct_drop fct_inorder
#' @importFrom lubridate years
#' @importFrom stringr str_split_fixed
#' @importFrom rlang .data
#' @return un dataframe filtré sur la région souhaitée
#' @export
data_prep <- function(reg, abc = TRUE, zone_a_secretiser = "", marches_a_secretiser = "") {
if (abc == FALSE) {
result <- indic_ecln %>%
COGiter::filtrer_cog(reg = reg, garder_supra = ">") %>%
dplyr::mutate(TypeZone = forcats::fct_relevel(.data$TypeZone, "France", "R\u00e9gions", "D\u00e9partements", "Epci")) %>%
dplyr::arrange(.data$TypeZone, .data$Zone) %>%
dplyr::mutate(
Zone = forcats::fct_drop(.data$Zone),
Zone = forcats::fct_inorder(.data$Zone),
marche = stringr::str_split_fixed(.data$Indicateur, "-", n = 2)[, 2],
Valeur = ifelse(.data$Zone %in% zone_a_secretiser &
.data$marche %in% marches_a_secretiser,
NA,
.data$Valeur
),
TauxEvolution12Mois = ifelse(.data$Zone %in% zone_a_secretiser &
.data$marche %in% marches_a_secretiser,
NA,
.data$TauxEvolution12Mois
)
)
}
if (abc == TRUE) {
result <- indic_ecln %>%
COGiter::filtrer_cog(reg = reg, garder_supra = ">")
abc <- indic_ecln %>%
dplyr::filter(.data$TypeZone == "ABC")
result <- dplyr::bind_rows(result, abc)
dplyr::mutate(TypeZone = forcats::fct_relevel(as.factor(.data$TypeZone), "France", "R\u00e9gions", "D\u00e9partements", "Epci", "ABC")) %>%
dplyr::arrange(.data$TypeZone, .data$Zone) %>%
dplyr::mutate(
Zone = forcats::fct_drop(.data$Zone),
Zone = forcats::fct_inorder(.data$Zone),
marche = stringr::str_split_fixed(.data$Indicateur, "-", n = 2)[, 2],
Valeur = ifelse(.data$Zone %in% zone_a_secretiser &
.data$marche %in% marches_a_secretiser,
NA,
.data$Valeur
),
TauxEvolution12Mois = ifelse(.data$Zone %in% zone_a_secretiser &
.data$marche %in% marches_a_secretiser,
NA,
.data$TauxEvolution12Mois
)
)
}
return(result)
}
utils::globalVariables(
c("liste_zone","indic_ecln","%m-%")
)
#' graphique sur un territoire sur un indicateur en moyenne annuelle et valeur trimestrielle
#'
#' @param data Le dataframe avec les données ecln.
#' @param indicateur L'indicateur à visualiser.
#' @param zone Le territoire sur lequel visualiser l'indicateur.
#' @param titre Le titre du graphique.
#'
#' @return un ggplot2
#' @export
#' @importFrom dplyr select distinct pull filter mutate
#' @importFrom forcats fct_recode
#' @importFrom ggforce geom_mark_circle
#' @importFrom ggplot2 ggplot aes geom_line geom_point margin theme labs guides scale_y_continuous scale_x_date
#' @importFrom glue glue
#' @importFrom gouvdown gouv_colors scale_color_gouv_discrete scale_fill_gouv_discrete
#' @importFrom grid unit
#' @importFrom lubridate quarter year
#' @importFrom stringr str_c
graphique_evolution_trim <- function(data = indic_ecln,
indicateur = "Ventes - Logements",
zone = "Pays de la Loire",
titre = "Ventes de logements neufs en Pays de la Loire") {
per <- data %>%
dplyr::select(.data$Periode) %>%
dplyr::distinct() %>%
dplyr::pull(.data$Periode)
max_date <- max(per)
sous_titre <- glue::glue("Au {label_rang(lubridate::quarter(max_date))} trimestre {lubridate::year(max_date)}")
label <- data %>%
dplyr::filter(
.data$Zone == zone,
.data$Indicateur == indicateur
) %>%
dplyr::filter(.data$Periode == max(.data$Periode)) %>%
dplyr::mutate(
Valeur = ifelse(.data$TypeIndicateur == "Cumul annuel", .data$Valeur / 4, .data$Valeur),
TypeIndicateur = forcats::fct_recode(.data$TypeIndicateur,
"Moyenne annuelle" = "Cumul annuel",
"Valeur trimestrielle" = "Trimestriel"
)
) %>%
dplyr::mutate(
description = stringr::str_c(
format(round(.data$Valeur), big.mark = " "),
"\n",
ifelse(.data$TauxEvolution12Mois > 0, "+", ""),
format(round(.data$TauxEvolution12Mois, 1), big.mark = " ", decimal.mark = ","),
" %"
),
label = ifelse(.data$TypeIndicateur %in% c("Valeur trimestrielle"),
FormatCaractere(.data$Periode),
"Moyenne\nannuelle"
)
)
gg <- data %>%
dplyr::filter(
.data$Zone == zone,
.data$Indicateur == indicateur
) %>%
dplyr::mutate(
Valeur = ifelse(.data$TypeIndicateur == "Cumul annuel", .data$Valeur / 4, .data$Valeur),
TypeIndicateur = forcats::fct_recode(.data$TypeIndicateur,
"Moyenne annuelle" = "Cumul annuel",
"Valeur trimestrielle" = "Trimestriel"
)
) %>%
ggplot2::ggplot() +
ggplot2::aes(x = .data$Periode, y = .data$Valeur, group = .data$TypeIndicateur, linetype = .data$TypeIndicateur, color = .data$TypeIndicateur) +
ggplot2::geom_line() +
ggplot2::geom_point(data = label, ggplot2::aes(x = .data$Periode, y = .data$Valeur, group = .data$TypeIndicateur, color = .data$TypeIndicateur)) +
ggforce::geom_mark_circle(
data = label, ggplot2::aes(
label = .data$label,
fill = .data$TypeIndicateur,
description = .data$description
),
label.buffer = grid::unit(5, "mm"),
expand = grid::unit(2, "mm"),
label.margin = ggplot2::margin(2, 5, 2, 5, "mm"),
label.colour = "white",
alpha = .5,
label.fill = gouvdown::gouv_colors("bleu_france")
) +
ggplot2::theme(legend.position = "bottom") +
gouvdown::scale_color_gouv_discrete(palette = "pal_gouv_qual2") +
gouvdown::scale_fill_gouv_discrete(palette = "pal_gouv_qual2") +
ggplot2::labs(
x = "",
y = "Nombre de ventes",
title = titre,
subtitle = sous_titre,
caption = "Source : ECLN\nMoyenne Annuelle : Valeur observ\u00e9e en moyenne sur les 4 derniers trimestres"
) +
ggplot2::guides(fill = F) +
ggplot2::scale_y_continuous(labels = function(l) format(l, scientific = FALSE, big.mark = " ", decimal.mark = ","), limits = c(0, NA)) +
ggplot2::scale_x_date(date_breaks = "1 year", date_labels = "%Y", limits = c(min(per), max(per) + months(12)))
return(gg)
}
#' Graphique d'évolution de l'investissement locatif
#'
#' @param data le dataframe avec les données ecln
#' @param type_logement Appartements ou Maisons
#' @param type_indicateur cumul annuel ou valeur trimestrielle
#' @param type_zone liste des types de zonage à intégrer dans la facette
#' @param titre titre du graphique
#' @param soustitre sous titre du graphique
#' @param bas_de_page bas de page
#'
#' @return Un graphique ggplot2.
#' @export
#' @importFrom dplyr filter mutate
#' @importFrom forcats fct_drop
#' @importFrom ggplot2 ggplot aes geom_area scale_x_date scale_y_continuous labs facet_wrap
#' @importFrom scales format_format
#' @importFrom stringr str_split_fixed
#'
#' @examples
graphique_investissement_locatif <- function(data = indic_ecln,
type_logement = "Appartements",
type_zone = c("R\u00e9gions","D\u00e9partements"),
type_indicateur = "Cumul annuel",
titre = "",
soustitre = "",
bas_de_page = "") {
indic <- c(
"Ventes hors investissement locatif - Appartements",
"Ventes en investissement locatif - Appartements"
)
if (type_logement == "Maisons") {
indic <- c(
"Ventes hors investissement locatif - Maisons",
"Ventes en investissement locatif - Maisons"
)
}
data_prep <- data %>%
dplyr::filter(
.data$Indicateur %in% indic,
.data$TypeIndicateur == type_indicateur,
.data$TypeZone %in% type_zone
) %>%
dplyr::mutate(
Zone = forcats::fct_drop(.data$Zone),
Indicateur = stringr::str_split_fixed(.data$Indicateur, " - ", 2)[, 1]
)
p <- ggplot2::ggplot(
data = data_prep,
ggplot2::aes(
x = .data$Periode,
y = .data$Valeur,
color = .data$Indicateur,
fill = .data$Indicateur,
group = .data$Indicateur
)
) +
ggplot2::geom_area(alpha = .5) +
ggplot2::scale_x_date(date_labels = "%y", date_breaks = "1 year") +
ggplot2::scale_y_continuous(labels = scales::format_format(big.mark = " ")) +
ggplot2::labs(
title = titre,
subtitle = soustitre,
x = "",
y = "",
fill = "",
color = "",
caption = bas_de_page
)
if (nlevels(data_prep$Zone) > 1) {
p <- p + ggplot2::facet_wrap(~Zone, scales = "free", ncol = 4)
}
return(p)
}
#' graphique en série temporelle à facette
#'
#' @param data Le dataframe avec les données ecln.
#' @param type_logement Appartements ou Maisons.
#' @param indicateurs Un vecteur d'indicateur à visualiser dans le graphique.
#' @param type_zone Liste des types de zonage à intégrer dans la facette.
#' @param titre Le titre du graphique.
#' @param bas_de_page Le bas de page du graphique.
#' @param ncol_facet Le nombre de colonnes dans la facette.
#' @return Un graphique ggplot2.
#' @export
#' @importFrom dplyr filter mutate
#' @importFrom ggplot2 ggplot aes geom_line facet_wrap scale_y_continuous scale_x_date labs
#' @importFrom gouvdown scale_color_gouv_discrete
#' @importFrom scales format_format
#' @examples
graphique_series_temporelles<-function(data=indic_ecln,
type_logement="Appartements",
indicateurs = c("Encours","Mises en vente","Ventes"),
type_zone = c("R\u00e9gions","D\u00e9partements"),
titre="",
bas_de_page="",
ncol_facet=4
){
indic <- paste0(indicateurs," - ",type_logement)
gg <- data %>%
dplyr::filter(.data$Indicateur %in% indic,
.data$TypeZone %in% type_zone,
.data$TypeIndicateur=="Cumul annuel") %>%
dplyr::mutate(Indicateur=str_split_fixed(.data$Indicateur," - ",2)[,1]) %>%
ggplot2::ggplot() +
ggplot2::aes(x=.data$Periode,y=.data$Valeur,color=.data$Indicateur,fill=.data$Indicateur,group=.data$Indicateur) +
ggplot2::geom_line(size=1.2)+
ggplot2::facet_wrap(~.data$Zone,scales="free",ncol=ncol_facet)+
ggplot2::scale_y_continuous(labels=scales::format_format(big.mark=" "),limits=c(0,NA)) +
ggplot2::scale_x_date(date_labels="%y",date_breaks = "1 year") +
gouvdown::scale_color_gouv_discrete(palette = "pal_gouv_qual2") +
ggplot2::labs(title=titre,
x="",
y="",
fill="",
color="",
caption=bas_de_page)
return(gg)
}
#' graphique sur l'évolution du prix de vente des biens.
#'
#' @param data Le dataframe.
#' @param type_logement Appartements ou Maisons.
#' @param type_indicateur Cumul annuel ou valeur trimestrielle.
#' @param type_zone Liste des types de zonage à intégrer dans la facette.
#' @param titre Le titre du graphique.
#' @param bas_de_page Le bas de page du graphique.
#'
#' @return Un graphique ggplot2.
#' @export
#' @importFrom dplyr filter mutate
#' @importFrom forcats fct_drop
#' @importFrom ggplot2 ggplot aes geom_line geom_point theme scale_x_date scale_y_continuous labs facet_wrap
#' @importFrom scales dollar_format
#' @importFrom stringr str_split_fixed
#' @importFrom gouvdown scale_color_gouv_discrete
#' @examples
graphique_series_temporelles_prix<-function(data=indic_ecln,
type_logement="Appartements",
type_zone = c("R\u00e9gions","D\u00e9partements"),
type_indicateur = "Cumul annuel",
titre="",
bas_de_page=""){
indic<-c("PrixM2 - Appartements")
if (type_logement=="Maisons") {
indic<- c("PrixPar - Maisons")
}
data_prep<-data %>%
dplyr::filter(.data$Indicateur %in% indic,
.data$TypeIndicateur == type_indicateur,
.data$TypeZone %in% type_zone) %>%
dplyr::mutate(Zone = forcats::fct_drop(.data$Zone),
Indicateur=stringr::str_split_fixed(.data$Indicateur," - ",2)[,1])
p<-ggplot2::ggplot(data_prep,
ggplot2::aes(x=.data$Periode,
y=.data$Valeur,
color=.data$Indicateur,
fill=.data$Indicateur,
group=.data$Indicateur)) +
ggplot2::geom_line(size=1.2)+
ggplot2::geom_point(data= data %>%
dplyr::filter(.data$Indicateur %in% indic,
.data$TypeIndicateur == type_indicateur,
.data$TypeZone %in% type_zone,
.data$Periode==max(.data$Periode)))+
ggplot2::theme(legend.position = "none")+
ggplot2::scale_x_date(date_labels="%y",date_breaks = "1 year")+
ggplot2::scale_y_continuous(labels=scales::dollar_format(big.mark=" ",decimal_mark=",",prefix="",suffix=" \u20ac"))+
gouvdown::scale_color_gouv_discrete(palette = "pal_gouv_qual2") +
ggplot2::labs(title=titre,
x="",
y="",
fill="",
color="",
caption=bas_de_page)
if (nlevels(data_prep$Zone)>1){
p<-p+ggplot2::facet_wrap(~Zone,scales="fixed",ncol=4)
}
return(p)
}
#' Table contenant les différents indicateurs de la source ecln utiles pour la publication.
#'
#' @encoding UTF-8
#' @format Table de `r nrow(indic_ecln)` lignes et `r ncol(indic_ecln)` colonnes:
#' \describe{
#' \item{TypeZone}{Type de territoire}
#' \item{CodeZone}{Code du territoire}
#' \item{Zone}{Libellé du territoire}
#' \item{TypeIndicateur}{valeur cumulée sur 12 mois ou trimestrielle}
#' \item{Indicateur}{Liste des indicateurs}
#' \item{Periode}{Trimestre d'observation}
#' \item{valeur}{Valeur de l'indicateur pour la modalité de variable}
#' \item{TauxEvolution12Mois}{Evolution de l'indicateur sur 12 mois glissant}
#' }
#' @source \url{https://www.statistiques.developpement-durable.gouv.fr/enquete-sur-la-commercialisation-des-logements-neufs-ecln}
"indic_ecln"
label_rang <- function(x) {
if (x == 1) {
res <- paste0(x,"er")
}
if (x == 2) {
res <- paste0(x,"nd")
}
if (x > 2) {
res <- paste0(x,"\u00e8me")
}
return(res)
}
#' tableau de synthèse des données en cumul annuel
#'
#' @param data Le dataframe.
#' @param type_logement Collectifs ou individuels.
#' @param type_zone Liste des types de zonage à intégrer dans la facette.
#' @return Un table kable
#' @importFrom dplyr filter mutate pull select full_join arrange
#' @importFrom kableExtra kable_styling row_spec add_header_above add_indent
#' @importFrom knitr kable
#' @importFrom stringr str_split_fixed
#' @importFrom tidyr spread
#' @export
tableau_synthese_annuel<-function(data = indic_ecln,
type_zone = c("France","R\u00e9gions","D\u00e9partements"),
type_logement = "collectif"
){
indic<-c("Encours - Appartements",
"Mises en vente - Appartements",
"Ventes - Appartements",
"PrixM2 - Appartements")
if (type_logement=="individuel") {
indic<- c("Encours - Maisons",
"Mises en vente - Maisons",
"Ventes - Maisons",
"PrixPar - Maisons")
}
input<-indic_ecln %>%
dplyr::filter(.data$Indicateur %in% indic,
.data$TypeZone %in% type_zone,
.data$TypeIndicateur=="Cumul annuel",
.data$Periode==max(.data$Periode)) %>%
dplyr::mutate(Indicateur=stringr::str_split_fixed(.data$Indicateur,"-",2)[,1])
nombre_zone <- length(unique(input$CodeZone))
nombre_fr_dep_reg <- length(unique(input %>% dplyr::filter(.data$TypeZone %in% c("R\u00e9gions","D\u00e9partements")) %>% dplyr::pull(.data$CodeZone)))
res<- input %>%
dplyr::select(.data$TypeZone,.data$Zone,.data$Indicateur,.data$Valeur) %>%
tidyr::spread(.data$Indicateur,.data$Valeur) %>%
dplyr::full_join(
input %>%
dplyr::select(.data$TypeZone,.data$Zone,.data$Indicateur,.data$TauxEvolution12Mois) %>%
tidyr::spread(.data$Indicateur,.data$TauxEvolution12Mois),
by=c("TypeZone","Zone")
) %>%
dplyr::arrange(.data$Zone) %>%
dplyr::select(2,6,10,4,8,3,7,5,9) %>%
knitr::kable("html",col.names=c("Zone","Sur les 12 derniers mois","Evolution sur un an (en %)",
"Sur les 12 derniers mois","Evolution sur un an (en %)",
"En fin de p\u00e9riode","Evolution sur un an (en %)",
"Prix moyen sur les 12 derniers mois (en €)","Evolution sur un an (en %)"),
digits=c(0,0,1,0,1,0,1,0,1),
format.args=list(big.mark=" ",decimal.mark=",")) %>%
kableExtra::kable_styling(font_size = 12) %>%
kableExtra::row_spec(1:2, bold = T, background = "#f0f0f5") %>%
kableExtra::add_header_above(c(" "=1, "Ventes" = 2, "Mises en vente" = 2, "Encours" = 2,"Prix au m2"=2)) %>%
kableExtra::add_indent(c(3:nombre_zone))
if("ABC" %in% type_zone){
res<-res %>%
kableExtra::row_spec(nombre_fr_dep_reg:nombre_zone, bold = T, background = "#bebece")
}
return(res)
}
#' Création du tableau de synthèse trimestrielle
#'
#' @param data Le dataframe.
#' @param type_logement Collectifs ou individuels.
#'
#' @return un tableau kable
#' @export
#' @importFrom dplyr filter mutate select full_join arrange
#' @importFrom kableExtra kable_styling row_spec add_header_above
#' @importFrom knitr kable
#' @importFrom stringr str_split_fixed
#' @importFrom tidyr spread
tableau_synthese_trimestrielle<-function(data = indic_ecln,
type_logement="collectif"){
indic<-c("Encours - Appartements",
"Mises en vente - Appartements",
"Ventes - Appartements",
"PrixM2 - Appartements")
if (type_logement=="individuel") {
indic<- c("Encours - Maisons",
"Mises en vente - Maisons",
"Ventes - Maisons",
"PrixPar - Maisons")
}
indic_ecln %>%
dplyr::filter(.data$Indicateur %in% indic,
.data$TypeZone %in% c("France","Régions"),
.data$TypeIndicateur != "Cumul annuel",
.data$Periode==max(.data$Periode)) %>%
dplyr::mutate(Indicateur=str_split_fixed(.data$Indicateur,"-",2)[,1]) %>%
dplyr::select(.data$TypeZone,.data$Zone,.data$Indicateur,.data$Valeur) %>%
tidyr::spread(.data$Indicateur,.data$Valeur) %>%
dplyr::full_join(
indic_ecln %>%
dplyr::filter(.data$Indicateur %in% indic,
.data$TypeZone %in% c("France","Régions"),
.data$TypeIndicateur!="Cumul annuel",
.data$Periode==max(.data$Periode)) %>%
dplyr::mutate(Indicateur=stringr::str_split_fixed(.data$Indicateur,"-",2)[,1]) %>%
dplyr::select(.data$TypeZone,.data$Zone,.data$Indicateur,.data$TauxEvolution12Mois) %>%
spread(.data$Indicateur,.data$TauxEvolution12Mois),
by=c("TypeZone","Zone")
) %>%
dplyr::arrange(.data$Zone) %>%
dplyr::select(2,6,10,4,8,3,7,5,9) %>%
knitr::kable("html",col.names=c("Zone","Sur le dernier trimestre","Evolution sur un an (en %)",
"Sur le dernier trimestre","Evolution sur un an (en %)",
"En fin de p\u00e9riode","Evolution sur un an (en %)",
"Prix moyen sur le dernier trimestre (en €)","Evolution sur un an (en %)"),
digits=c(0,0,1,0,1,0,1,0,1),
format.args=list(big.mark=" ",decimal.mark=",")) %>%
kableExtra::kable_styling(font_size = 12) %>%
kableExtra::row_spec(1:2, bold = T, background = "#f0f0f5") %>%
kableExtra::add_header_above(c(" "=1, "Ventes" = 2, "Mises en vente" = 2, "Encours" = 2,"Prix au m2"=2))
}
#' Pipe operator
#'
#' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details.
#'
#' @name %>%
#' @rdname pipe
#' @keywords internal
#' @export
#' @importFrom magrittr %>%
#' @usage lhs \%>\% rhs
NULL
## code to prepare `data-raw-ecln-sas.R` dataset goes here
library(magrittr)
library(haven)
library(readxl)
library(lubridate)
library(conflicted)
# devtool::install_github("MaelTheuliere/COGiter")
library(COGiter)
library(purrr)
library(dplyr)
library(tidyr)
library(forcats)
library(lubridate)
library(stringr)
library(glue)
library(dtplyr)
options(scipen = 999)
conflict_prefer("filter", "dplyr")
conflict_prefer("lag", "dplyr")
conflict_prefer("union", "dplyr")
conflict_prefer("setdiff", "dplyr")
source("R/FormatDate.R")
trimestre <- fs::dir_ls(path = "extdata", type = "directory") %>%
stringr::str_replace_all("extdata/","") %>%
max()
trimestre_date <- FormatDate(trimestre, Periodicite = "Trim", sep = "T")
trimestre_min <- FormatCaractere(trimestre_date-years(5)-months(3))
file_sas <- glue("extdata/{trimestre}/stat_info_data_regionaux.sas7bdat")
file_redressement <- glue("extdata/{trimestre}/{trimestre}rd1-commercialisation-lgts-neufs.xls")
ECLN <- read_sas(file_sas)
# Rajout du taux de redressement sur les mises en vente et le stoc --------
valeur_redressees <- excel_sheets(path = file_redressement)[4:length(excel_sheets(path = file_redressement))] %>%
map(~ read_excel(
path = file_redressement, sheet = .x,
range = "B10:Q10",
col_names = F
) %>%
select(1:5, 12:14) %>%
setNames(nm = c(
"Annee", "Periode", "Mises en vente - Appartements", "c_nb_resa", "Encours - Appartements",
"Mises en vente - Maisons", "i_nb_resa", "Encours - Maisons"
)) %>%
mutate(
Periode = paste0(Annee, Periode),
REG = .x
) %>%
select(REG, everything(), -Annee, -c_nb_resa, -i_nb_resa)) %>%
bind_rows() %>%
gather(Indicateur, Valeur, -REG, -Periode)
# calcul des indicateurs sur la carte des communes contenue dans ecln
# passage des données au cog à jour
indic_ecln <- ECLN %>%
select(DEPCOM = code_insee, Periode = trim_mev, id_type_lgt, mev_t) %>%
as_tibble() %>%
filter(Periode >= trimestre_min) %>%
group_by(id_type_lgt, DEPCOM, Periode) %>%
summarise(mev_t = sum(mev_t, na.rm = T)) %>%
ungroup() %>%
full_join(ECLN %>%
select(DEPCOM = code_insee, Periode = trimestre_enquete, everything()) %>%
filter(Periode >= trimestre_min) %>%
mutate(
nb_lgt_inv = nb_lgt_inv_t1 + nb_lgt_inv_t2 + nb_lgt_inv_t3 + nb_lgt_inv_t4 + nb_lgt_inv_t5 + nb_lgt_inv_t6,
nb_hors_resa_inv = nb_resa - nb_lgt_inv
) %>%
group_by(id_type_lgt, DEPCOM, Periode) %>%
summarise(
nb_resa = sum(nb_resa, na.rm = T),
nb_resa_inv = sum(nb_lgt_inv, na.rm = T),
nb_hors_resa_inv = sum(nb_hors_resa_inv, na.rm = T),
stock_fin = sum(stock_fin, na.rm = T),
prix = sum(prix, na.rm = T),
surface = sum(surface, na.rm = T)
) %>%
ungroup()) %>%
gather(Indicateur, Valeur, mev_t:surface) %>%
mutate(
Periode = factor(Periode),
id_type_lgt = factor(id_type_lgt),
DEPCOM = factor(DEPCOM),
id_type_lgt = fct_recode(id_type_lgt, Maisons = "1", Appartements = "2"),
Indicateur = fct_recode(factor(Indicateur), `Mises en vente` = "mev_t", Ventes = "nb_resa", `Ventes en investissement locatif` = "nb_resa_inv", `Ventes hors investissement locatif` = "nb_hors_resa_inv", Encours = "stock_fin", Prix = "prix", Surface = "surface"),
Indicateur = str_c(Indicateur, " - ", id_type_lgt)
) %>%
select(-id_type_lgt) %>%
mutate(Valeur = ifelse(is.na(Valeur),0,Valeur)) %>%
passer_au_cog_a_jour(code_commune = DEPCOM, aggrege = T, garder = F) %>%
right_join(communes %>% select(DEPCOM)) %>%
complete(DEPCOM, Periode, Indicateur,
fill = list(Valeur = 0)
) %>%
filter(!is.na(Indicateur), !is.na(Periode)) %>%
passer_au_cog_a_jour(code_commune = DEPCOM, aggrege = T, garder = T) %>%
select(REG, DEPCOM, Periode, Indicateur, Valeur) %>%
mutate_if(is.character, as.factor)
# On ne garde que les régions métro
indic_ecln <- indic_ecln %>%
filter(!(REG %in% c("01", "02", "03", "04", "05", "06")))
rm(ECLN)
taux_redressement <- indic_ecln %>%
filter(
Indicateur %in% unique(valeur_redressees$Indicateur),
as.character(REG) %in% unique(valeur_redressees$REG),
Periode == max(as.character(Periode))
) %>%
select(REG, Periode, Indicateur, Valeur) %>%
group_by(REG, Periode, Indicateur) %>%
summarise_all(funs(sum)) %>%
ungroup() %>%
left_join(valeur_redressees, by = c("REG", "Periode", "Indicateur")) %>%
mutate(taux_redressement = ifelse(Valeur.x > 0, Valeur.y / Valeur.x, 1)) %>%
select(REG, Periode, Indicateur, taux_redressement)
indic_ecln <- indic_ecln %>%
left_join(taux_redressement) %>%
mutate(Valeur = ifelse(Periode == max(Periode) & Indicateur %in% unique(valeur_redressees$Indicateur),
Valeur * taux_redressement,
Valeur
)) %>%
select(-taux_redressement, -REG) %>%
mutate_if(is.character, as.factor)
# Calcul sur total logements ----------------------------------------------
indic_ecln <- bind_rows(
indic_ecln,
indic_ecln %>%
mutate(Indicateur = str_split_fixed(Indicateur, " - ", 2)[, 1] %>% str_c(" - Logements") %>% as.factor()) %>%
group_by_if(is.factor) %>%
summarise_all(funs(sum(., na.rm = T))) %>%
ungroup()
) %>%
mutate_if(is.character, as.factor)
# Aggrégation de l'ensemble des calculs sur les zones -----------------------------------
indic_ecln <- indic_ecln %>%
group_split(Periode) %>%
furrr::future_map_dfr(cogifier)
# Rajout des zones abc
# update 2019
# zonage_abc_r52<-zonage_abc_r52 %>%
# passer_au_cog_a_jour(aggrege = F,garder_info_supra = F) %>%
# distinct() %>%
# arrange(DEPCOM,zonage_abc) %>%
# group_by(DEPCOM) %>%
# slice(1) %>%
# ungroup()
indic_ecln_abc <- indic_ecln %>%
filter(TypeZone == "Communes", CodeZone %in% (liste_zone %>%
filter(str_detect(REG, "52"), TypeZone == "Communes") %>%
pull(CodeZone))) %>%
left_join(zonage_abc, by = c("CodeZone" = "DEPCOM")) %>%
select(zonage_abc, Periode, Indicateur, Valeur) %>%
rename(CodeZone = zonage_abc) %>%
mutate(
Zone = CodeZone,
TypeZone = "ABC"
) %>%
group_by(TypeZone, Zone, CodeZone, Periode, Indicateur) %>%
summarise(Valeur = sum(Valeur)) %>%
ungroup()
# indic_ecln_pinel <- indic_ecln %>%
# filter(TypeZone == "Communes", CodeZone %in% (liste_zone %>%
# filter(str_detect(REG, "52"), TypeZone == "Communes") %>%
# pull(CodeZone))) %>%
# left_join(zonage_pinel_r52, by = c("CodeZone" = "DEPCOM")) %>%
# select(zonage_pinel, Periode, Indicateur, Valeur) %>%
# rename(CodeZone = zonage_pinel) %>%
# mutate(
# Zone = CodeZone,
# TypeZone = "Pinel"
# ) %>%
# group_by(TypeZone, Zone, CodeZone, Periode, Indicateur) %>%
# summarise(Valeur = sum(Valeur)) %>%
# ungroup()
# Aggrégation de l'ensemble des calculs sur les zones -----------------------------------
indic_ecln <- bind_rows(indic_ecln, indic_ecln_abc)%>%
arrange(TypeZone, Zone, CodeZone, Indicateur, Periode) %>%
filter(TypeZone != "Communes")
rm(list=setdiff(ls(),c("indic_ecln","FormatDate")))
# Utilisation du package dtplyr pour la performance
indicateurs_non_sommables <- str_subset(levels(indic_ecln$Indicateur),"Encours")
indic_ecln <- indic_ecln %>%
lazy_dt() %>%
group_by(TypeZone, Zone, CodeZone, Indicateur) %>%
mutate(Valeur_cumul = Valeur + lag(Valeur) + lag(Valeur, 2) + lag(Valeur, 3)
) %>%
ungroup() %>%
mutate(Valeur_cumul=ifelse(Indicateur %in% indicateurs_non_sommables,Valeur,Valeur_cumul)) %>%
as_tibble()
# Calcul des valeurs trimestrielles et cumul annuel ---------------------------
indic_ecln_trim <- indic_ecln %>%
select(-Valeur_cumul) %>%
mutate(Indicateur = str_replace_all(Indicateur, " - ", "_")) %>%
spread(Indicateur, Valeur, fill = 0) %>%
mutate(
PrixM2_Maisons = Prix_Maisons / Surface_Maisons,
PrixM2_Appartements = Prix_Appartements / Surface_Appartements,
PrixM2_Logements = Prix_Logements / Surface_Logements,
PrixPar_Maisons = Prix_Maisons / Ventes_Maisons,
PrixPar_Appartements = Prix_Appartements / Ventes_Appartements,
PrixPar_Logements = Prix_Logements / Ventes_Logements
) %>%
gather(Indicateur, Valeur, Encours_Appartements:PrixPar_Logements) %>%
mutate(
Indicateur = str_replace_all(Indicateur, "_", " - "),
Periode = FormatDate(Periode, Periodicite = "Trim", sep = "T"),
Source = "ECLN",
TypeIndicateur = "Trimestriel"
) %>%
filter(Periode > "2010-01-01")
indic_ecln_cumul <- indic_ecln %>%
select(-Valeur) %>%
mutate(Indicateur = str_replace_all(Indicateur, " - ", "_")) %>%
spread(Indicateur, Valeur_cumul, fill = 0) %>%
mutate(
PrixM2_Maisons = Prix_Maisons / Surface_Maisons,
PrixM2_Appartements = Prix_Appartements / Surface_Appartements,
PrixM2_Logements = Prix_Logements / Surface_Logements,
PrixPar_Maisons = Prix_Maisons / Ventes_Maisons,
PrixPar_Appartements = Prix_Appartements / Ventes_Appartements,
PrixPar_Logements = Prix_Logements / Ventes_Logements
) %>%
gather(Indicateur, Valeur, Encours_Appartements:PrixPar_Logements) %>%
mutate(
Indicateur = str_replace_all(Indicateur, "_", " - "),
Periode = FormatDate(Periode, Periodicite = "Trim", sep = "T"),
Source = "ECLN",
TypeIndicateur = "Cumul annuel"
) %>%
filter(Periode > "2011-01-01")
# Aggrétation finale -----
TauxEvolution12Mois <- function(.data) {
.data %>%
arrange(Source, TypeZone, Zone, CodeZone, TypeIndicateur, Indicateur) %>%
select(Source, TypeZone, Zone, CodeZone, TypeIndicateur, Indicateur, Periode, Valeur) %>%
group_by(Source, TypeZone, Zone, CodeZone, TypeIndicateur, Indicateur) %>%
mutate(TauxEvolution12Mois = round(100 * Valeur / lag(Valeur, 4) - 100, 1)) %>%
ungroup()
}
indic_ecln_cumul <- TauxEvolution12Mois(indic_ecln_cumul)
indic_ecln_trim <- TauxEvolution12Mois(indic_ecln_trim)
indic_ecln <- bind_rows(indic_ecln_cumul, indic_ecln_trim) %>%
mutate_if(is.character, as.factor) %>%
mutate(TypeZone = fct_relevel(TypeZone, "France", "Régions", "Départements", "Epci", "ABC"))
usethis::use_data(indic_ecln, overwrite = TRUE)
usethis::create_package(".")
usethis::use_gpl3_license()
usethis::use_build_ignore("devstuff.R")
usethis::use_data_raw("data-raw-ecln-sas.R")
usethis::use_build_ignore("extdata/")
usethis::use_r("FormatDate.R")
usethis::use_package('dplyr')
usethis::use_package('lubridate')
usethis::use_package('stringr')
usethis::use_r("creer_graphique_evolution_annuelle")
usethis::use_r('data_prep')
usethis::use_r('globals')
usethis::use_r("graphique_series_temporelles")
usethis::use_r("graphique_evolution_trim")
usethis::use_r("label_rang")
usethis::use_pipe()
usethis::use_r("indic_ecln")
usethis::use_r("graphique_investissement_locatif.R")
devtools::check()
usethis::use_r("graphique_series_temporelles_prix")
usethis::use_r("tableau_synthese_annuelle")
usethis::use_package('kableExtra')
usethis::use_package('knitr')
usethis::use_package('tidyr')
usethis::use_r("tableau_synthese_trimestrielle")
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment