Trabajo Practico N° 1

Modulo 6

Correlacion y regresion lineal simple

A Exploracion de datos

#install.packages("readxl")
library(readxl)
library(lmtest)
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
library(tidyverse)   
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.2     ✔ tibble    3.2.1
## ✔ lubridate 1.9.4     ✔ tidyr     1.3.1
## ✔ purrr     1.0.4
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(summarytools) 
## Warning in fun(libname, pkgname): couldn't connect to display ":0"
## system might not have X11 capabilities; in case of errors when using dfSummary(), set st_options(use.x11 = FALSE)
## 
## Attaching package: 'summarytools'
## 
## The following object is masked from 'package:tibble':
## 
##     view
library(dplyr)
library(PerformanceAnalytics)
## Loading required package: xts
## 
## ######################### Warning from 'xts' package ##########################
## #                                                                             #
## # The dplyr lag() function breaks how base R's lag() function is supposed to  #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or       #
## # source() into this session won't work correctly.                            #
## #                                                                             #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop           #
## # dplyr from breaking base R's lag() function.                                #
## #                                                                             #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning.  #
## #                                                                             #
## ###############################################################################
## 
## Attaching package: 'xts'
## 
## The following objects are masked from 'package:dplyr':
## 
##     first, last
## 
## 
## Attaching package: 'PerformanceAnalytics'
## 
## The following object is masked from 'package:graphics':
## 
##     legend

1 Carga de datos

nitrogeno <- read_excel("NITROGENO.xlsx")
### Ver las primeras filas
head(nitrogeno)
## # A tibble: 6 × 3
##   REPETICION PROFUNDIDAD NITROGENO
##        <dbl>       <dbl>     <dbl>
## 1          1          20      0.09
## 2          2          20      0.08
## 3          3          20      0.13
## 4          4          20      0.11
## 5          1          40      0.06
## 6          2          40      0.08

2 Explorar la estructura

glimpse(nitrogeno)
## Rows: 12
## Columns: 3
## $ REPETICION  <dbl> 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4
## $ PROFUNDIDAD <dbl> 20, 20, 20, 20, 40, 40, 40, 40, 60, 60, 60, 60
## $ NITROGENO   <dbl> 0.09, 0.08, 0.13, 0.11, 0.06, 0.08, 0.09, 0.09, 0.04, 0.05…

3 Grafico de dispersion

ggplot(nitrogeno, aes(PROFUNDIDAD,NITROGENO)) +
  geom_point()

ggplot(nitrogeno, aes(PROFUNDIDAD, NITROGENO, colour= REPETICION)) + 
  geom_point(shape = 17, size= 4, alpha= 1.0) +
  labs(x = "PROFUNDIDAD (cm)",
       y = "NITROGENO(%)") +
  theme_minimal()

# Paquete PerformanceAnalytics
chart.Correlation(nitrogeno, 
                  histogram = TRUE, 
                  method = "pearson", 
                  pch = 1)

B Analisis de correlacion Relación entre la profundidad y contenido de nitrogeno

4 Calculo coeficiente de Pearson

### Supuesto de Normalidad

### H0: Se cumple el supuesto de Normalidad
### H1: No se cumple el supuesto de Normalidad

shapiro.test(nitrogeno$PROFUNDIDAD)
## 
##  Shapiro-Wilk normality test
## 
## data:  nitrogeno$PROFUNDIDAD
## W = 0.81079, p-value = 0.01246
shapiro.test(nitrogeno$NITROGENO)
## 
##  Shapiro-Wilk normality test
## 
## data:  nitrogeno$NITROGENO
## W = 0.94544, p-value = 0.5716

La prueba de Shapiro da un p,valor de 0.01246 para la profundidad, este valor es menor que 0,05, por lo tanto rechazo Ho, osea que no hay normalidad. Para el nitrogeno la prueba da normalidad.

No deberia hacer Pearson, seria mejor hacer Sperman, pero como el problema pide Pearson realizamos la prueba.

Correlación de Pearson

Ho: No hay correlacion

Ha: Hay correlacion

cor.test(nitrogeno$PROFUNDIDAD, nitrogeno$NITROGENO, method = "pearson", conf.level = 0.95)
## 
##  Pearson's product-moment correlation
## 
## data:  nitrogeno$PROFUNDIDAD and nitrogeno$NITROGENO
## t = -5.0034, df = 10, p-value = 0.0005346
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  -0.9556210 -0.5271611
## sample estimates:
##        cor 
## -0.8453206

Valor del coeficiente= -0,8453

El signo negativo indica que a medida que la profundidad aumenta el contenido de nitrogeno disminuye

5 Evaluar hipotesis

Ho: coeficiente de correlacion = 0

H1: coeficiente de correlacion ≠ 0

Como el p-valor (0.000534) es menor que 0,05, rechazo la hipotesis nula, osea hay correlacion

C Regresion lineal simple

Ecuacion de la recta Y=α+βX+εY=𝛼+𝛽X+𝜀

####Donde: ####• 𝛼: ordenada al origen (intercepto). ####• 𝛽: pendiente de la recta. ####• 𝜀: error

regresion_nitrogeno <- lm(nitrogeno$NITROGENO ~ nitrogeno$PROFUNDIDAD)
regresion_nitrogeno
## 
## Call:
## lm(formula = nitrogeno$NITROGENO ~ nitrogeno$PROFUNDIDAD)
## 
## Coefficients:
##           (Intercept)  nitrogeno$PROFUNDIDAD  
##              0.131667              -0.001375

Y= 0,1317 - 0,0014 x

7

####El intercepto es la ordenada al origen #### El coeficiente de pendiente da la pendiente de la recta de regresion #### Significa que a medida que la profundidad aumenta el contenido de nitrogeno disminuye.

Resumen estadístico del modelo

summary(regresion_nitrogeno)
## 
## Call:
## lm(formula = nitrogeno$NITROGENO ~ nitrogeno$PROFUNDIDAD)
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -0.024167 -0.010417  0.002083  0.011458  0.025833 
## 
## Coefficients:
##                         Estimate Std. Error t value Pr(>|t|)    
## (Intercept)            0.1316667  0.0118732  11.089 6.11e-07 ***
## nitrogeno$PROFUNDIDAD -0.0013750  0.0002748  -5.003 0.000535 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.01555 on 10 degrees of freedom
## Multiple R-squared:  0.7146, Adjusted R-squared:  0.686 
## F-statistic: 25.03 on 1 and 10 DF,  p-value: 0.0005346

8

β1 = 0 (no hay relación lineal)

β1 ≠ 0 (sí hay relación lineal)

El p-valor para el coeficiente beta es 0,000535 osea es menor que 0,005, rechazo Ho por lo tanto hay relacion lineal

9

El R cuadrado es de 71,4 % osea que podemos decir que hay un buen ajuste a la recta de regresion

10 Grafico

ggplot(nitrogeno, aes(PROFUNDIDAD, NITROGENO)) + geom_point(size = 2.5, alpha = 1) +
  geom_smooth(method = "lm", se = FALSE, color = "red") +  geom_text(x = 50, y = 0.12, label = "y = 0,1317 - 0,0013 x", size = 5)
## `geom_smooth()` using formula = 'y ~ x'

D Diagnostico del modelo

11

summary(regresion_nitrogeno)
## 
## Call:
## lm(formula = nitrogeno$NITROGENO ~ nitrogeno$PROFUNDIDAD)
## 
## Residuals:
##       Min        1Q    Median        3Q       Max 
## -0.024167 -0.010417  0.002083  0.011458  0.025833 
## 
## Coefficients:
##                         Estimate Std. Error t value Pr(>|t|)    
## (Intercept)            0.1316667  0.0118732  11.089 6.11e-07 ***
## nitrogeno$PROFUNDIDAD -0.0013750  0.0002748  -5.003 0.000535 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 0.01555 on 10 degrees of freedom
## Multiple R-squared:  0.7146, Adjusted R-squared:  0.686 
## F-statistic: 25.03 on 1 and 10 DF,  p-value: 0.0005346

12 Supuestos de regresion

Análisis gráfico

#Usamos la función plot
par(mfrow=c(2,2)) # permite visualizar los gráficos de residuos en una sola imagen
plot(regresion_nitrogeno)

En base al QQ-plot sobre los residuos podemos suponer que se cumple la normalidad

Pruebas formales para los supuestos

####Normalidad

Ho: los residuos tienen distribución normal.

H1: los residuos NO tienen distribución normal.

RESIDUOS <- residuals(regresion_nitrogeno)
shapiro.test(RESIDUOS)
## 
##  Shapiro-Wilk normality test
## 
## data:  RESIDUOS
## W = 0.97087, p-value = 0.9197

Como El p-valor es mayor a 0,05 no rechazamos Ho osea los residuos tienen una distribucion normal

####Linealidad

Se evalúa graficamente (Residuals vs Fitted).

Homocedasticidad

Ho: Se cumple el supuesto de homocedasticidad

H1: No se cumple el supuesto de homocedasticidad

bptest(nitrogeno$PROFUNDIDAD~nitrogeno$NITROGENO, data = nitrogeno)
## 
##  studentized Breusch-Pagan test
## 
## data:  nitrogeno$PROFUNDIDAD ~ nitrogeno$NITROGENO
## BP = 0.18172, df = 1, p-value = 0.6699

Como el p.valor 0,669 es mayor que 0,05 no rechazo Ho osea hay homocedasticidad

E Prediccion

Contenido_nitrogeno = 0.1317 - 0.0014 * 50
Contenido_nitrogeno
## [1] 0.0617

Gráfico de dispersión con recta de Regresión y predicción

ggplot(nitrogeno, aes(PROFUNDIDAD, NITROGENO)) + geom_point(size = 2.5, alpha = 1) +
  geom_smooth(method = "lm", se = FALSE, color = "black") +  geom_text(x = 50, y = 0.12, label = "y = 0,1317 - 0,0013 x", size = 5) + geom_point(aes(x = 50, y = 0.0617), color = "red", size = 3.0)