Vamos a llevar a cabo 2 estudios respecto a los precios del carburante en base a:

Carga de librerías

library(quantmod)
library(ggplot2)
library(plyr)
library(grid)
library(gridExtra)
library(scales)
library(rgdal)
library(gdata)
library(sp)

Constantes

brent.barril <- 'DCOILBRENTEU'
precios.combustible.path <- 'src/precio_combustible.csv'
precios.medios.path <- 'src/PRECIOS_SHP_23022015.xls'
municipios.path <- 'src/shapefile'
municipios.shapefile <- 'municipios'

Funciones

Función para formatear fechas para el dataset precioCombust

createDate <- function(anio, mes){
  date_month <- ifelse(nchar(mes) == 1, paste(anio, mes, sep='-0'), paste(anio, mes, sep='-'))
  return(as.Date(paste(date_month, c('01'), sep='-'), format="%Y-%m-%d"))
}

Main

Gasolina 95 y Gasóleo – Barril Brent

Carga de datos de la Gasolina 95 y el Gasoleo A del año 2000 al 2015

Fuente

precioCombust <- read.csv(precios.combustible.path, header = TRUE, sep = ';')

Estructura del dataset precioCombust

head(precioCombust)
##   GASOLINA ANYO MES  PRECIO
## 1       95 2000   1 0.74923
## 2       95 2000   2 0.76656
## 3       95 2000   3 0.79436
## 4       95 2000   4 0.80112
## 5       95 2000   5 0.81453
## 6       95 2000   6 0.84040

Limpiamos el dataset para adaptar la fecha, formateada correctamente con formato aaaa-mm-dd, en una única columna

combustibles <- data.frame(fecha = createDate(precioCombust$ANYO, precioCombust$MES),
                           tipo = precioCombust$GASOLINA,
                           precio = precioCombust$PRECIO)

Muestra del dataset combustibles

head(combustibles)
##        fecha tipo  precio
## 1 2000-01-01   95 0.74923
## 2 2000-02-01   95 0.76656
## 3 2000-03-01   95 0.79436
## 4 2000-04-01   95 0.80112
## 5 2000-05-01   95 0.81453
## 6 2000-06-01   95 0.84040

Carga de datos del barril brent

getSymbols(brent.barril, src='FRED')

Muestra del dataset del precio del barril de Brent ($)

head(DCOILBRENTEU)
##            DCOILBRENTEU
## 1987-05-20        18.63
## 1987-05-21        18.45
## 1987-05-22        18.55
## 1987-05-25        18.60
## 1987-05-26        18.63
## 1987-05-27        18.60

Agrupamos mensualmente el dataset del Brent tomando como referencia el precio de cierre

brent_monthly <- to.monthly(DCOILBRENTEU['2000::'])[,c(4)]

Filtramos desde el primer mes del 2000 hasta ahora y formateamos la fecha en formato aaaa-mm-dd

df.brent <- data.frame(fecha = as.Date(format(index(brent_monthly), "%Y-%m-%d")),
                       tipo = c('brent'), 
                       precio = coredata(brent_monthly)[,1])

Muestra de df.brent

head(df.brent)
##        fecha  tipo precio
## 1 2000-01-01 brent  27.08
## 2 2000-02-01 brent  29.01
## 3 2000-03-01 brent  23.98
## 4 2000-04-01 brent  23.79
## 5 2000-05-01 brent  29.64
## 6 2000-06-01 brent  31.58

Concatenamos df.brent bajo combustible para tener todos los tipos en un dataframe

df.total <- rbind(combustibles, df.brent)

Gráfica

graficaGasolina <- ggplot(combustibles, aes(fecha, precio, shape = tipo, colour = tipo)) + 
                   geom_line(aes(group = tipo)) + 
                   theme(legend.position = "top", axis.text.x = element_blank(),
                         axis.ticks = element_blank(), axis.title.x = element_blank()) + 
                   scale_x_date(labels = date_format("%Y"), breaks = "3 month") 
graficaBrent <- ggplot(df.brent, aes(fecha, precio, shape = tipo, colour = tipo)) + 
                geom_line(aes(group = tipo)) + 
                theme(legend.position = "top", axis.text.x = element_text(angle = 90)) + 
                scale_x_date(labels = date_format("%Y-%b"), breaks = "3 month")
grid.arrange(graficaGasolina, graficaBrent, ncol=1) 

Viendo las correlaciones de ambos tipos de combustible contra el barril Brent, se puede observar que es un 1% mayor con el Gasóleo que con la Gasolina 95

cor(combustibles[combustibles$tipo == 95, c('precio')], df.brent$precio)
## [1] 0.940297
cor(combustibles[combustibles$tipo == 'GASOLEO_A', c('precio')], df.brent$precio)
## [1] 0.9571202

Comparativa de precios Comunidad de Madrid

Descargamos el fichero de datos con los datos de ambos combustibles de la comunidad y creamos el dataframe

Fuente

precMedio.gasoleo <- read.xls(precios.medios.path, sheet = "promedio_gasoleo", header = TRUE, 
                              colClasses = c("Provincia" = "character", "Localidad" = "character",
                                             "TIPO" = "character", "GEOCODIGO" = "character"),
                              stringsAsFactors = FALSE)

#Limpiamos columnas sobrantes
DatosGasoleo <- precMedio.gasoleo[,1:5] 

Muestra de los datos del Gasóleo

head(DatosGasoleo)
##   Provincia         Localidad PrecioGasoleo    TIPO GEOCODIGO
## 1    MADRID           AJALVIR      1.159000 GASOLEO      0029
## 2    MADRID        ALAMO (EL)      1.111667 GASOLEO      0040
## 3    MADRID ALCALA DE HENARES      1.156778 GASOLEO      0053
## 4    MADRID        ALCOBENDAS      1.183471 GASOLEO      0066
## 5    MADRID          ALCORCON      1.113000 GASOLEO      0072
## 6    MADRID  ALDEA DEL FRESNO      1.159000 GASOLEO      0088
precMedio.gasolina <- read.xls(precios.medios.path, sheet = "promedio_gasolina", header = TRUE, 
                               colClasses=c("Provincia" = "character", "Localidad" = "character",
                                            "TIPO" = "character", "GEOCODIGO" = "character"),  
                               stringsAsFactors = FALSE)

#Limpiamos columnas sobrantes
DatosGasolina <- precMedio.gasolina[,1:5]

Muestra de los datos de la Gasolina

head(DatosGasolina)
##   Provincia         Localidad PrecioGasolina        TIPO GEOCODIGO
## 1    MADRID           AJALVIR       1.199000 GASOLINA 95      0029
## 2    MADRID        ALAMO (EL)       1.204000 GASOLINA 95      0040
## 3    MADRID ALCALA DE HENARES       1.220176 GASOLINA 95      0053
## 4    MADRID        ALCOBENDAS       1.214813 GASOLINA 95      0066
## 5    MADRID          ALCORCON       1.174739 GASOLINA 95      0072
## 6    MADRID  ALDEA DEL FRESNO       1.219000 GASOLINA 95      0088

Cargamos el shapefile con los datos geoespaciales de los municipios de Madrid

municipios <- readOGR(dsn = municipios.path, layer = municipios.shapefile)

Extraemos los datos geospatial a través de la función fortify de los municipios y hacemos el join con la parte @data de dicho objeto de clase SpatialPolygonsDataFrame

municipios@data$id <- rownames(municipios@data)
municipios.df <- fortify(municipios)
municipios.df <- join(municipios.df, municipios@data, by="id")

Muestra de municipios.df

head(municipios.df)
##       long     lat order  hole piece group id CODBDT GEOCODIGO      DESBDT
## 1 449269.0 4547740     1 FALSE     1   0.1  0 754123      0014 Acebeda, La
## 2 449109.6 4547659     2 FALSE     1   0.1  0 754123      0014 Acebeda, La
## 3 448944.3 4547620     3 FALSE     1   0.1  0 754123      0014 Acebeda, La
## 4 448948.9 4547637     4 FALSE     1   0.1  0 754123      0014 Acebeda, La
## 5 448954.0 4547658     5 FALSE     1   0.1  0 754123      0014 Acebeda, La
## 6 448957.3 4547676     6 FALSE     1   0.1  0 754123      0014 Acebeda, La

Unimos el dataframe municipios.df con los 2 anteriores dataframe que tienen los precios de la Gasolina y el Gasóleo por municipio

municipios.df <- join(municipios.df, DatosGasolina, by = c('GEOCODIGO'), type = "inner")
municipios.df <- join(municipios.df, DatosGasoleo, by = c('GEOCODIGO', 'Localidad', 'Provincia'), 
                      type = 'inner')

Muestra del join resultante

head(municipios.df)
##       long     lat order  hole piece group id CODBDT GEOCODIGO  DESBDT
## 1 459224.8 4489965     1 FALSE     1   1.1  1 754124      0029 Ajalvir
## 2 459200.5 4489734     2 FALSE     1   1.1  1 754124      0029 Ajalvir
## 3 459356.7 4489771     3 FALSE     1   1.1  1 754124      0029 Ajalvir
## 4 459355.9 4489646     4 FALSE     1   1.1  1 754124      0029 Ajalvir
## 5 459355.9 4489646     5 FALSE     1   1.1  1 754124      0029 Ajalvir
## 6 459339.6 4489594     6 FALSE     1   1.1  1 754124      0029 Ajalvir
##   Provincia Localidad PrecioGasolina        TIPO PrecioGasoleo    TIPO
## 1    MADRID   AJALVIR          1.199 GASOLINA 95         1.159 GASOLEO
## 2    MADRID   AJALVIR          1.199 GASOLINA 95         1.159 GASOLEO
## 3    MADRID   AJALVIR          1.199 GASOLINA 95         1.159 GASOLEO
## 4    MADRID   AJALVIR          1.199 GASOLINA 95         1.159 GASOLEO
## 5    MADRID   AJALVIR          1.199 GASOLINA 95         1.159 GASOLEO
## 6    MADRID   AJALVIR          1.199 GASOLINA 95         1.159 GASOLEO

Gráfica

plotGasolina <- ggplot(data=municipios.df, aes(x=long, y=lat, group=group)) +
                geom_polygon(aes(fill = PrecioGasolina)) +
                theme(legend.position = "bottom", axis.ticks = element_blank(), 
                      axis.text.x = element_blank(), axis.title.x = element_blank(), 
                      axis.text.y = element_blank(), axis.title.y = element_blank()) +
                labs(title="Precio medio Gasolina 95 por municipio") +
                #geom_path(color="grey", linestyle=2) + # draw boundaries
                coord_equal() +
                scale_fill_gradient(low = "#F5FBEF", high = "#38610B", space = "Lab",
                                    na.value = "grey50", guide = "colourbar")
plotGasoleo <- ggplot(data=municipios.df, aes(x=long, y=lat, group=group)) +
               geom_polygon(aes(fill = PrecioGasoleo)) +
               theme(legend.position = "bottom", axis.ticks = element_blank(), 
                     axis.text.x = element_blank(), axis.title.x = element_blank(), 
                     axis.text.y = element_blank(), axis.title.y = element_blank()) +
               labs(title="Precio medio Gasoleo A por municipio") +
               #geom_path(color="grey", linestyle=2) + # draw boundaries
               coord_equal() +
               scale_fill_gradient(low = "#FBEFEF", high = "#610B0B", space = "Lab", 
                                   na.value = "grey50", guide = "colourbar")
grid.arrange(plotGasolina, plotGasoleo, ncol=2)