Caricamento dei pacchetti necessari

library(readr)
library(dplyr)
library(moments)
library(ggplot2)
library(knitr)

Caricamento del dataset

realestate_texas <- read_csv("C:/Users/OEM/Desktop/realestate_texas.csv")
## Rows: 240 Columns: 8
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (1): city
## dbl (7): year, month, sales, volume, median_price, listings, months_inventory
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Visualizzazione delle prime righe del dataset

kable(head(realestate_texas))
city year month sales volume median_price listings months_inventory
Beaumont 2010 1 83 14.162 163800 1533 9.5
Beaumont 2010 2 108 17.690 138200 1586 10.0
Beaumont 2010 3 182 28.701 122400 1689 10.6
Beaumont 2010 4 200 26.819 123200 1708 10.6
Beaumont 2010 5 202 28.833 123100 1771 10.9
Beaumont 2010 6 189 27.219 122800 1803 11.1

Definizione delle variabili:

Calcolo degli indici statistici

summary_stats <- realestate_texas %>%
  select(-year, -month) %>% 
  select_if(is.numeric) %>% 
  reframe(
    Mean = sapply(., function(x) round(mean(x), 2)),
    Median = sapply(., function(x) round(median(x), 2)),
    SD = sapply(., function(x) round(sd(x), 2)),
    CV = sapply(., function(x) round(sd(x) / mean(x) * 100, 2)),
    Skewness = sapply(., function(x) round(skewness(x), 2)),
    Kurtosis = sapply(., function(x) round(kurtosis(x), 2))
  )

summary_stats_transposed <- t(summary_stats)

kable(summary_stats_transposed, 
      col.names = c("Statistic", names(realestate_texas %>% select(sales, volume, median_price, listings, months_inventory))))
Statistic sales volume median_price listings months_inventory
Mean 192.29 31.01 132665.42 1738.02 9.19
Median 175.50 27.06 134500.00 1618.50 8.95
SD 79.65 16.65 22662.15 752.71 2.30
CV 41.42 53.71 17.08 43.31 25.06
Skewness 0.72 0.88 -0.36 0.65 0.04
Kurtosis 2.69 3.18 2.38 2.21 2.83

Analisi delle variabili:

Identificazione delle variabili con maggiore variabilità e asimmetria:

Tra tutte le variabili, il volume delle vendite (volume) si distingue per avere la variabilità più alta, con un coefficiente di variazione del 53.71%. Questo significa che il valore totale delle vendite varia notevolmente da un mese all’altro, con alcuni mesi che registrano picchi significativi. Questa variabilità potrebbe essere legata a fattori stagionali, eventi economici o strategie di marketing particolarmente efficaci in determinati periodi.

Inoltre, il volume delle vendite è anche la variabile con la distribuzione più asimmetrica, con una skewness di 0.88. Questo indica che la maggior parte dei mesi ha un volume di vendite relativamente basso, ma ci sono alcuni mesi con valori eccezionalmente alti che “spingono” la distribuzione verso destra

Creazione delle classi per median_price

realestate_texas$price_class <- cut(realestate_texas$median_price, 
                                    breaks = seq(min(realestate_texas$median_price), 
                                                 max(realestate_texas$median_price), 
                                                 length.out = 6), 
                                    include.lowest = TRUE, 
                                    labels = c("Basso", "Medio-basso", "Medio", "Medio-alto", "Alto"))
table(realestate_texas$price_class)
## 
##       Basso Medio-basso       Medio  Medio-alto        Alto 
##          18          40          73          84          25

Grafico a barre

ggplot(realestate_texas, aes(x = price_class)) +
  geom_bar(fill = "steelblue", color = "black") +
  labs(title = "Distribuzione delle Classi di Prezzo", x = "Classi di Prezzo", y = "Frequenza") +
  theme_minimal()

La classe più frequente è Medio-alto, con 84 osservazioni, seguita dalla classe Medio con 73 osservazioni. Le classi Basso e Alto sono le meno rappresentate, con rispettivamente 18 e 25 osservazioni. Questo suggerisce che la maggior parte degli immobili ha un prezzo mediano nella fascia medio-alta, mentre pochi immobili si trovano nelle fasce più basse o più alte.

Indice di Eterogeneità Gini per median_price

gini.index <- function(x){
  ni=table(x)
  fi=ni/length(x)
  fi2 = fi^2
  J = length(table(x))
  
  gini = 1-sum(fi2)
  gini.normalizzato = gini/((J-1)/J)
  
  return(gini.normalizzato)
}
gini_median_price <- gini.index(realestate_texas$price_class)
cat("Indice di Eterogeneità di Gini per median_price:", round(gini_median_price, 2), "\n")
## Indice di Eterogeneità di Gini per median_price: 0.93

L’indice di Gini è 0.93, un valore molto vicino a 1. Questo indica un’elevata eterogeneità nella distribuzione dei prezzi. In altre parole, i prezzi degli immobili non sono uniformemente distribuiti tra le classi, ma sono concentrati in alcune fasce specifiche (in particolare, quelle Medio e Medio-alto).

Calcolo delle probabilità

prob_beaumont <- round(sum(realestate_texas$city == "Beaumont") / nrow(realestate_texas) * 100, 2)

prob_july <- round(sum(realestate_texas$month == 7) / nrow(realestate_texas) * 100, 2)

prob_december_2012 <- round(sum(realestate_texas$month == 12 & realestate_texas$year == 2012) / nrow(realestate_texas) * 100, 2)

cat("Probabilità che la città sia Beaumont:", prob_beaumont, "%\n")
## Probabilità che la città sia Beaumont: 25 %
cat("Probabilità che il mese sia Luglio:", prob_july, "%\n")
## Probabilità che il mese sia Luglio: 8.33 %
cat("Probabilità che il mese sia Dicembre 2012:", prob_december_2012, "%\n")
## Probabilità che il mese sia Dicembre 2012: 1.67 %

Creazione di nuove variabili:

realestate_texas <- realestate_texas %>%
  mutate(average_price = round(volume * 1e6 / sales, 2),
         listing_effectiveness = round(sales / listings, 2))

realestate_texas <- realestate_texas %>%
  mutate(average_price = round(volume * 1e6 / sales, 2),
         listing_effectiveness = round(sales / listings, 2))

summary_stats <- realestate_texas %>%
  select(-year, -month) %>%  
  select_if(is.numeric) %>%  
  reframe(
    Mean = sapply(., function(x) round(mean(x), 2)),
    Median = sapply(., function(x) round(median(x), 2)),
    SD = sapply(., function(x) round(sd(x), 2)),
    CV = sapply(., function(x) round(sd(x) / mean(x) * 100, 2)),
    Skewness = sapply(., function(x) round(skewness(x), 2)),
    Kurtosis = sapply(., function(x) round(kurtosis(x), 2))
  )

summary_stats_transposed <- t(summary_stats)

kable(summary_stats_transposed, 
      col.names = c("Statistic", names(realestate_texas %>% select(sales, volume, median_price, listings, months_inventory, average_price, listing_effectiveness))))
Statistic sales volume median_price listings months_inventory average_price listing_effectiveness
Mean 192.29 31.01 132665.42 1738.02 9.19 154320.37 0.12
Median 175.50 27.06 134500.00 1618.50 8.95 156588.48 0.11
SD 79.65 16.65 22662.15 752.71 2.30 27147.46 0.05
CV 41.42 53.71 17.08 43.31 25.06 17.59 39.77
Skewness 0.72 0.88 -0.36 0.65 0.04 -0.07 2.10
Kurtosis 2.69 3.18 2.38 2.21 2.83 2.22 10.01

Analisi condizionata

summary_city <- realestate_texas %>%
  group_by(city) %>%
  summarise(
    mean_sales = mean(sales, na.rm = TRUE),  
    sd_sales = sd(sales, na.rm = TRUE)       
  )

summary_year <- realestate_texas %>%
  group_by(year) %>%
  summarise(
    mean_sales = mean(sales, na.rm = TRUE),  
    sd_sales = sd(sales, na.rm = TRUE)       
  )

summary_month <- realestate_texas %>%
  group_by(month) %>%
  summarise(
    mean_sales = mean(sales, na.rm = TRUE),  
    sd_sales = sd(sales, na.rm = TRUE)       
  )

kable(summary_city, digits = 2, align = "c", caption = "Media e deviazione standard delle vendite per città")
Media e deviazione standard delle vendite per città
city mean_sales sd_sales
Beaumont 177.38 41.48
Bryan-College Station 205.97 84.98
Tyler 269.75 61.96
Wichita Falls 116.07 22.15
kable(summary_year, digits = 2, align = "c", caption = "Media e deviazione standard delle vendite per anno")
Media e deviazione standard delle vendite per anno
year mean_sales sd_sales
2010 168.67 60.54
2011 164.12 63.87
2012 186.15 70.91
2013 211.92 84.00
2014 230.60 95.51
kable(summary_month, digits = 2, align = "c", caption = "Media e deviazione standard delle vendite per mese")
Media e deviazione standard delle vendite per mese
month mean_sales sd_sales
1 127.40 43.38
2 140.85 51.07
3 189.45 59.18
4 211.70 65.40
5 238.85 83.12
6 243.55 95.00
7 235.75 96.27
8 231.45 79.23
9 182.35 72.52
10 179.90 74.95
11 156.85 55.47
12 169.40 60.75

Rappresentazione grafica dei risultati

ggplot(summary_city, aes(x = city, y = mean_sales)) +
  geom_bar(stat = "identity", fill = "steelblue", alpha = 0.8) + 
  geom_errorbar(aes(ymin = mean_sales - sd_sales, ymax = mean_sales + sd_sales), 
                width = 0.2, color = "red") + 
  theme_minimal() + 
  theme(axis.text.x = element_text(angle = 0, hjust = 0.5)) + 
  labs(title = "Media e deviazione standard delle vendite per città", 
       x = "Città", 
       y = "Vendite medie") 

ggplot(summary_year, aes(x = year, y = mean_sales)) +
  geom_line(color = "blue", size = 1) + 
  geom_point(color = "blue", size = 2) + 
  geom_errorbar(aes(ymin = mean_sales - sd_sales, ymax = mean_sales + sd_sales), 
                width = 0.2, color = "red") +
  theme_minimal() + 
  labs(title = "Media e deviazione standard delle vendite per anno", 
       x = "Anno", 
       y = "Vendite medie") +
  scale_x_continuous(breaks = summary_year$year) 
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

ggplot(summary_month, aes(x = month, y = mean_sales)) +
  geom_line(color = "blue", size = 1) + 
  geom_point(color = "blue", size = 2) + 
  geom_errorbar(aes(ymin = mean_sales - sd_sales, ymax = mean_sales + sd_sales), 
                width = 0.2, color = "red") +
  theme_minimal() + 
  scale_x_continuous(breaks = 1:12, 
                     labels = c("Gen", "Feb", "Mar", "Apr", "Mag", "Giu", 
                                "Lug", "Ago", "Set", "Ott", "Nov", "Dic")) + 
  labs(title = "Media e deviazione standard delle vendite per mese", 
       x = "Mese", 
       y = "Vendite medie")

Boxplot per la distribuzione del prezzo mediano tra le città:

ggplot(realestate_texas, aes(x = city, y = median_price)) +
  geom_boxplot() +
  labs(title = "Distribuzione del Prezzo Mediano per Città", x = "Città", y = "Prezzo Mediano")

Il grafico Boxplot mostra che:

Considerazioni:

Grafico a barre per il totale delle vendite per mese e città:

ggplot(realestate_texas, aes(x = factor(month), y = sales, fill = city)) +
  geom_bar(stat = "identity", position = "stack", alpha = 0.85) + 
  scale_x_discrete(labels = c("Gen", "Feb", "Mar", "Apr", "Mag", "Giu", 
                              "Lug", "Ago", "Set", "Ott", "Nov", "Dic")) + 
  scale_fill_brewer(palette = "Set3") +
  theme_minimal() + 
  theme(
    legend.position = "bottom", 
    legend.title = element_blank(),
    axis.text.x = element_text(angle = 0, hjust = 0.5) 
  ) +
  labs(title = "Totale delle Vendite per Mese e Città", 
       x = "Mese", 
       y = "Totale Vendite")  

ggplot(realestate_texas, aes(x = factor(month), y = sales, fill = city)) +
  geom_bar(stat = "identity", position = "fill", alpha = 0.85) + 
  scale_x_discrete(labels = c("Gen", "Feb", "Mar", "Apr", "Mag", "Giu", 
                              "Lug", "Ago", "Set", "Ott", "Nov", "Dic")) + 
  scale_fill_brewer(palette = "Set3") +
  theme_minimal() + 
  theme(
    legend.position = "bottom", 
    legend.title = element_blank(),
    axis.text.x = element_text(angle = 0, hjust = 0.5) 
  ) +
  labs(title = "Totale delle Vendite per Mese e Città", 
       x = "Mese", 
       y = "Totale Vendite")

ggplot(realestate_texas, aes(x = interaction(month, year), y = sales, fill = city)) +
  geom_bar(stat = "identity", position = "stack", alpha = 0.85) + 
  scale_x_discrete(labels = function(x) {
    paste0(substr(x, 1, 2), "-", substr(x, 3, 7))
  }) +
  scale_fill_brewer(palette = "Set3") +
  theme_minimal() + 
  theme(
    legend.position = "bottom", 
    legend.title = element_blank(),
    axis.text.x = element_text(angle = 45, hjust = 1, size = 6)  
  ) +
  labs(title = "Totale delle Vendite per Mese, Città e Anno", 
       x = "Mese-Anno", 
       y = "Proporzione delle Vendite")+
  geom_vline(xintercept = seq(12.5, by = 12, length.out = length(unique(realestate_texas$year)) - 1), 
             linetype = "dashed", color = "gray", size = 0.5)  

Sono stati creati 3 grafici, il primo è un grafico a barre per il totale delle vendite per mese e città, il secondo grafico mostra la proporzione delle vendite per ogni mese rispetto al totale annuo, infine il terzo include la variabile year.

Dai risultati si evince che:

Quindi, i mesi primaverili ed estivi (marzo-agosto) sono i più favorevoli per le vendite in tutte le città.

Tyler è la città con il maggior numero di vendite, mentre Wichita Falls ha le vendite più basse.

Line Charts per l’andamento delle vendite nel tempo per città:

ggplot(realestate_texas, aes(x = year, y = sales, color = city, group = city)) +
  geom_line() + 
  geom_point() +
  scale_color_brewer(palette = "Set1") + 
  theme_minimal() +
  theme(
    legend.position = "bottom", 
    legend.title = element_blank(), 
    axis.text.x = element_text(angle = 45, hjust = 1), 
    panel.grid.major.y = element_line(color = "gray90", size = 0.5) 
  ) +
  labs(title = "Andamento delle Vendite nel Tempo per Città", 
       x = "Anno", 
       y = "Vendite")
## Warning: The `size` argument of `element_line()` is deprecated as of ggplot2 3.4.0.
## ℹ Please use the `linewidth` argument instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

ggplot(realestate_texas, aes(x = year, y = sales, color = city, group = city)) +
  geom_line() + 
  geom_point() +
  scale_color_brewer(palette = "Set1") + 
  facet_wrap(~ city) +
  theme_minimal() +
  theme(
    legend.position = "bottom", 
    legend.title = element_blank(), 
    axis.text.x = element_text(angle = 45, hjust = 1), 
    panel.grid.major.y = element_line(color = "gray90", size = 0.5) 
  ) +
  labs(title = "Andamento delle Vendite nel Tempo per Città", 
       x = "Anno", 
       y = "Vendite")

Il grafico mostra che:

Considerazioni:

Conclusioni

Tyler si distingue come la città con la crescita più marcata, sia in termini di vendite che di prezzi mediani. Le vendite sono aumentate costantemente nel tempo, raggiungendo picchi significativi nei mesi estivi. Questo suggerisce un mercato in forte espansione, con immobili di fascia alta che attirano acquirenti disposti a investire.

Bryan-College Station, invece, mostra un andamento più volatile, con picchi di vendita significativi in alcuni mesi e cali in altri. Questa variabilità potrebbe essere legata a fattori stagionali o eventi economici locali. Nonostante la volatilità, la città ha un mercato attivo, con un prezzo mediano più alto rispetto a Beaumont e Wichita Falls. La presenza di mesi con efficacia degli annunci particolarmente alta suggerisce che ci sono strategie di marketing che funzionano meglio in determinati periodi, che potrebbero essere replicate per migliorare le performance complessive.

Beaumont ha un mercato più stabile, con vendite medie più basse rispetto a Tyler e Bryan-College Station, ma con una crescita moderata nel tempo. I mesi estivi sono i più favorevoli per le vendite, ma la città non raggiunge i livelli di performance delle altre due. Tuttavia, la presenza di alcuni immobili con prezzi più bassi rispetto alla media potrebbe attrarre acquirenti con budget limitato, offrendo opportunità per diversificare l’offerta.

Infine, Wichita Falls è la città con le vendite medie più basse e un andamento più stabile nel tempo. Nonostante la bassa variabilità, il mercato rimane poco dinamico, con un leggero aumento delle vendite nei mesi estivi. Questa stabilità potrebbe essere un’opportunità per adottare strategie mirate, come campagne di marketing specifiche o offerte promozionali, per stimolare la domanda e aumentare le vendite.

In sintesi, Tyler e Bryan-College Station rappresentano le opportunità più promettenti, con mercati in crescita e picchi di vendita significativi. Beaumont e Wichita Falls, invece, richiedono strategie più mirate per sfruttare il potenziale di mercato e migliorare le performance.