# Instalar y cargar el paquete readxl (si no lo tienes)
if (!requireNamespace("readxl", quietly = TRUE)) {
  install.packages("readxl")
}


library(readxl)
## Warning: package 'readxl' was built under R version 4.4.2
Primer_Asignacion_Dic_06_1_ <- read_excel("C:/Users/Usuario/Desktop/Primer Asignacion Dic 06 (1).xlsx")
View(Primer_Asignacion_Dic_06_1_)

file_path <- "C:/Users/Usuario/Desktop/Primer Asignacion Dic 06 (1).xlsx"

# Leer la hoja "Hoja1"
data <- read_excel(file_path, sheet = "Hoja1")

# Inspeccionar los primeros datos
head(data)
## # A tibble: 6 × 3
##    Year Month  Temp
##   <dbl> <dbl> <dbl>
## 1  2005    11   6.1
## 2  2005    12   5.2
## 3  2006     1   7.2
## 4  2006     2   5.5
## 5  2006     3   7.6
## 6  2006     4  10
#Se realiza una limpieza de datos, nos quedamos con las columnas Year, Month y Temp, eliminando filas con valores faltantes.

# Seleccionar columnas relevantes
clean_data <- data[, c("Year", "Month", "Temp")]

# Convertir a formato data.frame (por si acaso)
clean_data <- as.data.frame(clean_data)

# Eliminar filas con datos faltantes
clean_data <- na.omit(clean_data)

# Revisar los datos limpios
head(clean_data)
##   Year Month Temp
## 1 2005    11  6.1
## 2 2005    12  5.2
## 3 2006     1  7.2
## 4 2006     2  5.5
## 5 2006     3  7.6
## 6 2006     4 10.0
summary(clean_data)
##       Year          Month             Temp      
##  Min.   :2005   Min.   : 1.000   Min.   : 5.20  
##  1st Qu.:2006   1st Qu.: 3.500   1st Qu.: 6.65  
##  Median :2006   Median : 6.000   Median :10.00  
##  Mean   :2006   Mean   : 6.182   Mean   :10.97  
##  3rd Qu.:2006   3rd Qu.: 8.500   3rd Qu.:15.50  
##  Max.   :2006   Max.   :12.000   Max.   :18.00
#a) Tendencia de temperatura a lo largo del tiempo
#Crearemos una columna de fechas para representar las temperaturas.

# Crear una columna de fecha
clean_data$Date <- as.Date(paste(clean_data$Year, clean_data$Month, "1", sep = "-"))

# Instalar y cargar ggplot2 (si no lo tienes)
if (!requireNamespace("ggplot2", quietly = TRUE)) {
  install.packages("ggplot2")
}

library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.2
# Graficar la tendencia
ggplot(clean_data, aes(x = Date, y = Temp)) +
  geom_line(color = "blue") +
  geom_point(color = "red") +
  ggtitle("Tendencia Mensual de Temperatura - Estación Black Rock") +
  xlab("Fecha") +
  ylab("Temperatura (°C)") +
  theme_minimal()

#b) Gráfica de cajas para estacionalidad mensual
#Esto ayuda a identificar patrones repetitivos por mes.

ggplot(clean_data, aes(x = as.factor(Month), y = Temp)) +
  geom_boxplot(fill = "red", color = "darkblue") +
  ggtitle("Distribución Mensual de Temperaturas") +
  xlab("Mes") +
  ylab("Temperatura (°C)") +
  theme_minimal()

#Calcularemos estadísticas clave: promedio, mediana y desviación estándar.

# Calcular estadísticas
mean_temp <- mean(clean_data$Temp)
median_temp <- median(clean_data$Temp)
sd_temp <- sd(clean_data$Temp)

# Mostrar resultados
list(mean = mean_temp, median = median_temp, sd = sd_temp)
## $mean
## [1] 10.97273
## 
## $median
## [1] 10
## 
## $sd
## [1] 4.956428
#modelos posibles:
  
#Modelo Lineal: Relaciona la temperatura con el tiempo.
#Modelo Polinomial: Considera curvas de segundo o tercer grado.
#Modelo Estacional: Utiliza series temporales para capturar patrones mensuales.

#Compararamos los modelos usando métricas como el Coeficiente de Determinación (R²) y el Error Cuadrático Medio (MSE).


#Ajuste de un modelo lineal 

# Modelo lineal simple: temperatura en función del tiempo
linear_model <- lm(Temp ~ Date, data = clean_data)

# Resumen del modelo
summary(linear_model)
## 
## Call:
## lm(formula = Temp ~ Date, data = clean_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.1827 -1.4605  0.2653  1.3984  2.9851 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -5.801e+02  9.206e+01  -6.301 0.000141 ***
## Date         4.464e-02  6.953e-03   6.420 0.000122 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.212 on 9 degrees of freedom
## Multiple R-squared:  0.8208, Adjusted R-squared:  0.8009 
## F-statistic: 41.22 on 1 and 9 DF,  p-value: 0.0001223
 #Ajuste de un mdelo polinomial 

# Modelo polinomial de grado 2
poly_model <- lm(Temp ~ poly(as.numeric(Date), 2), data = clean_data)

# Resumen del modelo
summary(poly_model)
## 
## Call:
## lm(formula = Temp ~ poly(as.numeric(Date), 2), data = clean_data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.1258 -1.4959  0.2615  1.4097  2.9807 
## 
## Coefficients:
##                            Estimate Std. Error t value Pr(>|t|)    
## (Intercept)                 10.9727     0.7072  15.515 2.96e-07 ***
## poly(as.numeric(Date), 2)1  14.1999     2.3456   6.054 0.000305 ***
## poly(as.numeric(Date), 2)2  -0.1106     2.3456  -0.047 0.963557    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.346 on 8 degrees of freedom
## Multiple R-squared:  0.8208, Adjusted R-squared:  0.776 
## F-statistic: 18.33 on 2 and 8 DF,  p-value: 0.00103
#Analisis estacional con series temporales 

# Verificar si hay meses faltantes
table(clean_data$Year, clean_data$Month)
##       
##        1 2 3 4 5 6 7 8 9 11 12
##   2005 0 0 0 0 0 0 0 0 0  1  1
##   2006 1 1 1 1 1 1 1 1 1  0  0
# Instalar paquete para manejar datos de tiempo
if (!requireNamespace("tidyr", quietly = TRUE)) install.packages("tidyr")
library(tidyr)

# Completar meses faltantes
clean_data <- complete(clean_data, Year, Month, fill = list(Temp = NA))

# Crear una serie temporal de temperaturas (frecuencia mensual)
temp_ts <- ts(clean_data$Temp, start = c(min(clean_data$Year), min(clean_data$Month)), frequency = 12)

# Verificar la serie temporal
temp_ts
##       Jan  Feb  Mar  Apr  May  Jun  Jul  Aug  Sep  Oct  Nov  Dec
## 2005   NA   NA   NA   NA   NA   NA   NA   NA   NA  6.1  5.2  7.2
## 2006  5.5  7.6 10.0 13.2 16.4 18.0 16.9 14.6   NA   NA
# Calcular MSE para el modelo lineal
mse_linear <- mean(residuals(linear_model)^2)

# Calcular MSE para el modelo polinomial
mse_poly <- mean(residuals(poly_model)^2)

# Mostrar los resultados
list(MSE_Linear = mse_linear, MSE_Polynomial = mse_poly)
## $MSE_Linear
## [1] 4.002314
## 
## $MSE_Polynomial
## [1] 4.001203
# Crear una columna de tiempo en formato decimal
data$Time <- data$Year + (data$Month - 1) / 12

# Inspeccionar los datos preparados
print(data)
## # A tibble: 11 × 4
##     Year Month  Temp  Time
##    <dbl> <dbl> <dbl> <dbl>
##  1  2005    11   6.1 2006.
##  2  2005    12   5.2 2006.
##  3  2006     1   7.2 2006 
##  4  2006     2   5.5 2006.
##  5  2006     3   7.6 2006.
##  6  2006     4  10   2006.
##  7  2006     5  13.2 2006.
##  8  2006     6  16.4 2006.
##  9  2006     7  18   2006.
## 10  2006     8  16.9 2007.
## 11  2006     9  14.6 2007.
# Ajuste del del modelo lineal
Modelo <- lm(Temp ~ Time, data = data)

# Resumen del modelo
summary(Modelo)
## 
## Call:
## lm(formula = Temp ~ Time, data = data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.1500 -1.4950  0.2936  1.3882  2.9609 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -32621.595   5050.220  -6.459 0.000117 ***
## Time            16.265      2.517   6.462 0.000117 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.2 on 9 degrees of freedom
## Multiple R-squared:  0.8227, Adjusted R-squared:  0.803 
## F-statistic: 41.75 on 1 and 9 DF,  p-value: 0.0001165
# Inspeccionar los primeros datos
head(data)
## # A tibble: 6 × 4
##    Year Month  Temp  Time
##   <dbl> <dbl> <dbl> <dbl>
## 1  2005    11   6.1 2006.
## 2  2005    12   5.2 2006.
## 3  2006     1   7.2 2006 
## 4  2006     2   5.5 2006.
## 5  2006     3   7.6 2006.
## 6  2006     4  10   2006.
# Crear una columna de tiempo en formato decimal
data$Time <- data$Year + (data$Month - 1) / 12

# Inspeccionar los datos preparados
print(data)
## # A tibble: 11 × 4
##     Year Month  Temp  Time
##    <dbl> <dbl> <dbl> <dbl>
##  1  2005    11   6.1 2006.
##  2  2005    12   5.2 2006.
##  3  2006     1   7.2 2006 
##  4  2006     2   5.5 2006.
##  5  2006     3   7.6 2006.
##  6  2006     4  10   2006.
##  7  2006     5  13.2 2006.
##  8  2006     6  16.4 2006.
##  9  2006     7  18   2006.
## 10  2006     8  16.9 2007.
## 11  2006     9  14.6 2007.
# Ajuste del del modelo lineal
Modelo <- lm(Temp ~ Time, data = data)

# Resumen del modelo
summary(Modelo)
## 
## Call:
## lm(formula = Temp ~ Time, data = data)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -3.1500 -1.4950  0.2936  1.3882  2.9609 
## 
## Coefficients:
##               Estimate Std. Error t value Pr(>|t|)    
## (Intercept) -32621.595   5050.220  -6.459 0.000117 ***
## Time            16.265      2.517   6.462 0.000117 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 2.2 on 9 degrees of freedom
## Multiple R-squared:  0.8227, Adjusted R-squared:  0.803 
## F-statistic: 41.75 on 1 and 9 DF,  p-value: 0.0001165
# Último valor de tiempo
Ultimo_tiempo <- max(data$Time)

# Nuevos puntos de predicción
Tiempo_futuro <- c(Ultimo_tiempo + 1/12, Ultimo_tiempo + 2/12)

# Predicciones
Predicciones <- predict(Modelo, newdata = data.frame(Time = Tiempo_futuro))

# Crear el data.frame con las predicciones
datos_predicciones <- data.frame(
  Time = Tiempo_futuro,
  Temp = Predicciones
)

# Graficar los resultados
ggplot(data, aes(x = Time, y = Temp)) +
  geom_point(color = "blue", size = 3) +  # Datos históricos
  geom_smooth(method = "lm", formula = y ~ x, color = "red", se = FALSE) +  # Línea de regresión
  geom_point(data = datos_predicciones, aes(x = Time, y = Temp), color = "green", size = 3) +  # Predicciones futuras
  labs(title = "Modelo de Predicción de Temperaturas", x = "Tiempo (Años)", y = "Temperatura (°C)") +
  theme_minimal()