Documentos de Académico
Documentos de Profesional
Documentos de Cultura
https://www.r-project.org/
Getting Started
Consola
Las funciones de R se agrupan en paquetes (packages, libraries), los que contienen las
funciones más habituales se incluyen por defecto en la distribución de R, y el resto se
encuentran disponibles en la Comprehensive R Archive Network (CRAN). Las entidades que R
crea y manipula se llaman objetos. Dichos objetos pueden ser: •Escalares: números,
caracteres, lógicos (booleanos), factores •Vectores/matrices/listas de escalares •Funciones
•Objetos ad-hoc Dichos objetos se guardan en un workspace. Durante una sesión de R todos
los objetos estarán en memoria, y se pueden guardar en disco para próximas sesiones
1
2
1) Paso 1, abrimos y fijamos directorio
3
Para fijar directorio: More- Save as orking directory
setwd("C:/Users/Usuario/Desktop/practica R clase")
2) Script
EL script está en blanco para poder guardar todo el trabajo que hacemos, el primer paso es
guardarlo y a partir de ahí escribimos las órdenes
4
# para ir comentando las notas de clase puedo escribirlo con la almohadilla
# podemos poner las líneas que queramos para acordarnos y compartir con el equipo
setwd("C:/Users/Usuario/Desktop/practica R clase")
Ya lo teníamos, pero de este modo queda en nuestro script para la próxima sesión, una vez que
# ahora vamos a cargar los datos y tenemos que saber si es csv, texto, spss...
library(readxl)
View(datos_pib_para_R)
En R prácticamente todo es definido como un objeto; un dato numérico, un vector, una matriz
de datos o una función, son objetos, y R opera sobre ellos. Cada objeto tiene un nombre, y el
hecho de escribirlo en la ventana de comandos hará que se muestre su contenido. R distingue
entre distintos tipos de objetos (no es lo mismo un vector, una matriz o una función) cada uno
de los cuales posee características propias, que en el entorno R se conocen como modo y
atributos. Los objetos son de un determinado tipo (mode) y tienen atributos (attributes). Un
objeto es en definitiva la forma en la que R almacena la información. Para obtener un listado
de los objetos disponibles en el espacio de trabajo pueden utilizarse las funciones ls() u
objects().
5
VAMOS A RENOMBRAR LAS VARIABLES PARA QUE SEA MÁS SENCILLO
names(datos_pib_para_R)[2] = "Gasto"
names(datos_pib_para_R)[3] = "PIB"
saveRDS(datos_pib_para_R,file = "datos.RDS")
plot(datos_pib_para_R$PIB)
$PIB la variable
plot(datos_pib_para_R$Gasto)
plot(datos_pib_para_R$Gasto,datos_pib_para_R$PIB)
6
#Sacamos la correlacion lineal entre el PIB y el consumo
cor(datos_pib_para_R$Gasto,datos_pib_para_R$PIB)
modelo_lineal<-lm
Autocorrelación
library(lmtest)
dwtest(modelo_lineal,alternative ="two.sided",iterations = 1000)
Durbin-Watson test
data: modelo_lineal
https://www.rpubs.com/Econ0metria/505378
Breusch-Godfrey Test
Description
Usage
bgtest(modelo_lineal)
7
data: modelo_lineal
Breusch-Godfrey Test
escription
Usage
Arguments
formula a symbolic description for the model to be tested (or a fitted "lm" object).
order.by Either a vector z or a formula with a single explanatory variable like ~ z. The
observations in the model are ordered by the size of z. If set to NULL (the default) the
observations are assumed to be ordered (e.g., a time series).
type the type of test statistic to be returned. Either "Chisq" for the Chi-squared test statistic
or "F" for the F test statistic.
data an optional data frame containing the variables in the model. By default the variables
are taken from the environment which bgtest is called from.
fill starting values for the lagged residuals in the auxiliary regression. By default 0 but can
also be set to NA.
Details
Under H_0 the test statistic is asymptotically Chi-squared with degrees of freedom as given in
parameter. If type is set to "F" the function returns a finite sample version of the test statistic,
employing an F distribution with degrees of freedom as given in parameter.
By default, the starting values for the lagged residuals in the auxiliary regression are chosen to
be 0 (as in Godfrey 1978) but could also be set to NA to omit them.
bgtest also returns the coefficients and estimated covariance matrix from the auxiliary
regression that includes the lagged residuals. Hence, coeftest can be used to inspect the
results. (Note, however, that standard theory does not always apply to the standard errors and
t-statistics in this regression.)
Value
A list with class "bgtest" inheriting from "htest" containing the following components:
8
p.value the p-value of the test.
HETEROCEDASTICIDAD
https://fhernanb.github.io/libro_regresion/homo.html
9
estimaciones alternativas
# Analizamos el modelo
summary(modelo_lineal_log)
Call:
Residuals:
Coefficients:
10
(Intercept) -4.37819 0.53710 -8.151 1.24e-08 ***
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
Durbin-Watson test
data: modelo_lineal_log
bgtest(modelo_lineal_log)
data: modelo_lineal_log
Breusch-Godfrey Test
bgtest(formula, order = 1, order.by = NULL, type = c("Chisq", "F"),
data = list(), fill = 0)
prueba_white_log<-bptest(modelo_lineal_log,~I(PIB^2),data = datos_pib_para_R)
data: modelo_lineal_log
11
#Para ver los residuos
modelo_lineal_log$residuals
install.packages("kableExtra")
remotes::install_github("haozhu233/kableExtra")
https://scpoecon.github.io/ScPoEconometrics/R-intro.html
12