U1A3
- Descargar archivos
xfun::embed_file("U2A3.Rmd")xfun::embed_file("datos.xlsx")xfun::embed_file("1.jpg")INTRODUCCION
La agricultura es el conjunto de actividades económicas y técnicas relacionadas con el tratamiento del suelo y el cultivo de la tierra para la producción de alimentos. Comprende todo un conjunto de acciones humanas que transforma el medio ambiente natural. Para México, la agricultura es una de las actividades prioritarias y más importantes, ya que no sólo genera gran cantidad de empleos, sino que también responde a las necesidades alimenticias de millones de personas, preserva los entornos naturales y estimula el progreso al mejorar la calidad de vida.
En el estado de Sonora la agricultura toma un lugar muy importante, ya que es uno de los principales motores que impulsan a la economía del estado y uno de los principales cultivos que se cosechan es la papa blanca, en el cual Sonora se mantiene como entidad líder a nivel nacional. En este estudio se análiza la regresión lineal múltiple la cual permite generar un modelo lineal en el que el valor de la variable dependiente o respuesta (Y) se determina a partir de un conjunto de variables independientes llamadas predictores.
REGRESION LINEAL MULTIPLE
La regresión lineal múltiple permite generar un modelo lineal en el que el valor de la variable dependiente o respuesta (Y ) se determina a partir de un conjunto de variables independientes llamadas predictores (X1 , X2 , X3 …). Es una extensión de la regresión lineal simple, por lo que es fundamental comprender esta última. Los modelos de regresión múltiple pueden emplearse para predecir el valor de la variable dependiente o para evaluar la influencia que tienen los predictores sobre ella (esto último se debe que analizar con cautela para no malinterpretar causa-efecto).
Los modelos lineales múltiples siguen la siguiente ecuación:
\[ Y_{i}=(\beta_{0}+\beta_{1}X_{1i}+\beta_{2}X_{2i}+\cdots+\beta_{n}X_{ni})+e_{i} \] * β0 es la ordenada en el origen, el valor de la variable dependiente Y cuando todos los predictores son cero.
βi : es el efecto promedio que tiene el incremento en una unidad de la variable predictora Xi sobre la variable dependiente Y , manteniéndose constantes el resto de variables. Se conocen como coeficientes parciales de regresión.
ei: es el residuo o error, la diferencia entre el valor observado y el estimado por el modelo.
setwd("~/ESTADISTICA APLICADA/U2A3")
library(pacman)
library(hpackedbubble)##
## Attaching package: 'hpackedbubble'
## The following object is masked from 'package:datasets':
##
## CO2
library(gplots)##
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
##
## lowess
library(psych)
library(GGally)## Loading required package: ggplot2
##
## Attaching package: 'ggplot2'
## The following objects are masked from 'package:psych':
##
## %+%, alpha
## Registered S3 method overwritten by 'GGally':
## method from
## +.gg ggplot2
library(car)## Loading required package: carData
##
## Attaching package: 'car'
## The following object is masked from 'package:psych':
##
## logit
library(gvlma)
library(strucchange)## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
## Loading required package: sandwich
library(xtable)
library(extrafont)## Registering fonts with R
library(normtest)
library(readr)
library(readxl)
library(prettydoc)
library(DT)
library(dplyr)##
## Attaching package: 'dplyr'
## The following object is masked from 'package:car':
##
## recode
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
library(ggplot2)
library(data.table)##
## Attaching package: 'data.table'
## The following objects are masked from 'package:dplyr':
##
## between, first, last
library(scales)##
## Attaching package: 'scales'
## The following object is masked from 'package:readr':
##
## col_factor
## The following objects are masked from 'package:psych':
##
## alpha, rescale
library(plotly)##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
library(tidyverse)## -- Attaching packages --------------------------------------- tidyverse 1.3.0 --
## v tibble 3.0.5 v stringr 1.4.0
## v tidyr 1.1.2 v forcats 0.5.1
## v purrr 0.3.4
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x ggplot2::%+%() masks psych::%+%()
## x scales::alpha() masks ggplot2::alpha(), psych::alpha()
## x data.table::between() masks dplyr::between()
## x stringr::boundary() masks strucchange::boundary()
## x scales::col_factor() masks readr::col_factor()
## x purrr::discard() masks scales::discard()
## x plotly::filter() masks dplyr::filter(), stats::filter()
## x data.table::first() masks dplyr::first()
## x dplyr::lag() masks stats::lag()
## x data.table::last() masks dplyr::last()
## x dplyr::recode() masks car::recode()
## x purrr::some() masks car::some()
## x purrr::transpose() masks data.table::transpose()
library(modelr)
library(lubridate)##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:data.table':
##
## hour, isoweek, mday, minute, month, quarter, second, wday, week,
## yday, year
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
library(datos)library(readxl)
agricultura <- read_excel("datos.xlsx")## New names:
## * `` -> ...1
View(agricultura)Superficie_sembrada <- agricultura$`Superficie_sembrada_(Ha)`
Superficie_cosechada <- agricultura$`Superficie_cosechada_(Ha)`
Superficie_siniestrada <- agricultura$`Superficie_siniestrada_(Ha)`
Produccion <- agricultura$`Produccion_(Ton)`
Precio_medio_rural <- agricultura$`Precio_medio_rural_(pesos/Ton)`
Valor_de_la_produccion <- agricultura$`Valor_de_la_produccion_(Millones_de_pesos)`
datos <- data.table(Superficie_sembrada, Superficie_cosechada, Superficie_siniestrada, Produccion, Precio_medio_rural, Valor_de_la_produccion)
round( cor( x = datos, method = "pearson"), 3)## Superficie_sembrada Superficie_cosechada
## Superficie_sembrada 1.000 0.989
## Superficie_cosechada 0.989 1.000
## Superficie_siniestrada 0.450 0.313
## Produccion 0.950 0.982
## Precio_medio_rural -0.026 -0.115
## Valor_de_la_produccion 0.981 0.996
## Superficie_siniestrada Produccion Precio_medio_rural
## Superficie_sembrada 0.450 0.950 -0.026
## Superficie_cosechada 0.313 0.982 -0.115
## Superficie_siniestrada 1.000 0.171 0.528
## Produccion 0.171 1.000 -0.228
## Precio_medio_rural 0.528 -0.228 1.000
## Valor_de_la_produccion 0.284 0.992 -0.139
## Valor_de_la_produccion
## Superficie_sembrada 0.981
## Superficie_cosechada 0.996
## Superficie_siniestrada 0.284
## Produccion 0.992
## Precio_medio_rural -0.139
## Valor_de_la_produccion 1.000
multi.hist(x = datos, dcol = c("blue", "red"), dlty = c("dotted", "solid"),main = "")library(GGally)
ggpairs(datos, lower = list(continuous = "smooth"),
diag = list(continuous = "barDiag"), axisLabels = "none")## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
Analisís preliminar de los predictores a utilizar
Las variables que tienen una mayor relación lineal con la produccion en toneladas son: valor de la produccion (r= 992), Superficie cosechada (r= 982) y Superficie sembrada (r= 0.95).
Valor de producción y Superficie sembrada están medianamente correlacionados (r = 0.981), tambien ek vakir de produccion y superficie cosechada (r=996) por lo que posiblemente no sea útil introducir esos 3 predictores en el modelo.
modelo <- lm(Produccion ~ Superficie_cosechada + Superficie_siniestrada + Produccion + Valor_de_la_produccion, data = datos )## Warning in model.matrix.default(mt, mf, contrasts): the response appeared on the
## right-hand side and was dropped
## Warning in model.matrix.default(mt, mf, contrasts): problem with term 3 in
## model.matrix: no columns are assigned
summary(modelo)##
## Call:
## lm(formula = Produccion ~ Superficie_cosechada + Superficie_siniestrada +
## Produccion + Valor_de_la_produccion, data = datos)
##
## Residuals:
## Min 1Q Median 3Q Max
## -2168.3 -647.5 -120.5 180.3 5591.6
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 143.385 756.609 0.190 0.8535
## Superficie_cosechada -10.643 5.789 -1.838 0.0959 .
## Superficie_siniestrada -25.057 3.337 -7.510 2.04e-05 ***
## Valor_de_la_produccion 180.801 21.201 8.528 6.70e-06 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 2168 on 10 degrees of freedom
## Multiple R-squared: 0.9982, Adjusted R-squared: 0.9977
## F-statistic: 1897 on 3 and 10 DF, p-value: 4.495e-14