Descargamos R desde la página https://cloud.r-project.org/bin/windows/base/R-3.6.1-win.exe Luego de la descarga se ejecuta el programa.
Posteriormente se descarga Rstudio desde le siguiente enlace https://download1.rstudio.org/desktop/windows/RStudio-1.2.5001.exe y se instala de manera similar. Es de aclarar que debe instalarse primero R y luego Rstudio. Al finalizar la instalación, se ejecuta el programa Rstudio.
A continuación los pasos para cargar una base de datos. Primero buscamos la opción de cargar la base de excel
## Estadística descriptiva ## Para este ejemplo, primero vamos a cargar la base de datos contenida en el enlace https://www.isid.ac.in/~deepayan/R-tutorials/data/iris.xls siguiendo las instrucciones anteriores y la llamaremos “iris”
Luego de realizar la carga de la base de datos, empezaremos abriendo un script de R,
En este script, se digitan las intrucciones para realizar las operaciones estadisticas, por ejemplo se escribe \(iris\) y luego ejecutamos con Ctrl+Enter obtenemos
iris
Si ejecutamos la opción
iris$Sepal.Length
## [1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.8 5.7 5.4
## [18] 5.1 5.7 5.1 5.4 5.1 4.6 5.1 4.8 5.0 5.0 5.2 5.2 4.7 4.8 5.4 5.2 5.5
## [35] 4.9 5.0 5.5 4.9 4.4 5.1 5.0 4.5 4.4 5.0 5.1 4.8 5.1 4.6 5.3 5.0 7.0
## [52] 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 5.2 5.0 5.9 6.0 6.1 5.6 6.7 5.6 5.8
## [69] 6.2 5.6 5.9 6.1 6.3 6.1 6.4 6.6 6.8 6.7 6.0 5.7 5.5 5.5 5.8 6.0 5.4
## [86] 6.0 6.7 6.3 5.6 5.5 5.5 6.1 5.8 5.0 5.6 5.7 5.7 6.2 5.1 5.7 6.3 5.8
## [103] 7.1 6.3 6.5 7.6 4.9 7.3 6.7 7.2 6.5 6.4 6.8 5.7 5.8 6.4 6.5 7.7 7.7
## [120] 6.0 6.9 5.6 7.7 6.3 6.7 7.2 6.2 6.1 6.4 7.2 7.4 7.9 6.4 6.3 6.1 7.7
## [137] 6.3 6.4 6.0 6.9 6.7 6.9 5.8 6.8 6.7 6.7 6.3 6.5 6.2 5.9
En la pantalla de Rstudio aparecera así |
Si ejecutamos entonces la base, seguida de $ obtendremos la variable que necesitamos
Si ejecutamos la funcion summary(variable) obtenemos las medidas de tendencia central de la variable
summary(iris$Sepal.Length)
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 4.300 5.100 5.800 5.843 6.400 7.900
Si ejecutamos la funcion var(variable) obtenemos varianza
var(iris$Sepal.Length)
## [1] 0.6856935
sd(iris$Sepal.Length)
## [1] 0.8280661
La función table(variable) arroja la tabla de frecuencias absolutas
table(iris$Species)
##
## setosa versicolor virginica
## 50 50 50
hist(iris$Sepal.Length)
Ahora con más estilo
hist(iris$Sepal.Length, xlab="Titulo eje x", ylab="Titulo eje y", main="Titulo", col="red")
boxplot(iris$Sepal.Length,xlab="Titulo eje x", ylab="Titulo eje y", main="Titulo")
pie(table(iris$Species),xlab="Titulo eje x", ylab="Titulo eje y", main="Titulo")
plot(iris$Sepal.Length, iris$Petal.Length, xlab="Titulo eje x", ylab="Titulo eje y", main="Titulo")
boxplot(iris$Sepal.Length~iris$Species, xlab="Titulo eje x", ylab="Titulo eje y", main="Titulo")
Con el comando lm se ejecuta una regresión lineal simple de la forma \(Y=A+BX\) donde \(X=Petal.Length\) y \(Y=Sepal.Length\)
lm(iris$Sepal.Length~iris$Petal.Length)
##
## Call:
## lm(formula = iris$Sepal.Length ~ iris$Petal.Length)
##
## Coefficients:
## (Intercept) iris$Petal.Length
## 4.3066 0.4089
Por lo cual la recta queda de la forma \(Y=4.3056+ 0.4097 X\) y si además ejecutamos
summary(lm(iris$Sepal.Length~iris$Petal.Length))
##
## Call:
## lm(formula = iris$Sepal.Length ~ iris$Petal.Length)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.24675 -0.29657 -0.01515 0.27676 1.00269
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 4.30660 0.07839 54.94 <2e-16 ***
## iris$Petal.Length 0.40892 0.01889 21.65 <2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.4071 on 148 degrees of freedom
## Multiple R-squared: 0.76, Adjusted R-squared: 0.7583
## F-statistic: 468.6 on 1 and 148 DF, p-value: < 2.2e-16
Obtenemos un \(R^2=76\%\)
Deseo contrastar si la longitud promedio del petalo es igual a 4 cm, se plantea la hipotesis \[ H_0:\mu =4\] \[H_a:\mu\neq 4\]
t.test(iris$Petal.Length, mu=4, alternative = "two.sided", conf.level = 0.95)
##
## One Sample t-test
##
## data: iris$Petal.Length
## t = -1.679, df = 149, p-value = 0.09525
## alternative hypothesis: true mean is not equal to 4
## 95 percent confidence interval:
## 3.473185 4.042815
## sample estimates:
## mean of x
## 3.758
Deseo contrastar si la longitud promedio del petalo es menor a 4 cm, se plantea la hipotesis \[ H_0:\mu \geq 4\] \[H_a:\mu < 4\]
t.test(iris$Petal.Length, mu=4, alternative = "less")
##
## One Sample t-test
##
## data: iris$Petal.Length
## t = -1.679, df = 149, p-value = 0.04763
## alternative hypothesis: true mean is less than 4
## 95 percent confidence interval:
## -Inf 3.996566
## sample estimates:
## mean of x
## 3.758
Deseo contrastar si la longitud promedio del petalo es mayor a 4 cm, se plantea la hipotesis \[ H_0:\mu > 4\] \[H_a:\mu \leq 4\]
t.test(iris$Petal.Length, mu=4, alternative = "greater")
##
## One Sample t-test
##
## data: iris$Petal.Length
## t = -1.679, df = 149, p-value = 0.9524
## alternative hypothesis: true mean is greater than 4
## 95 percent confidence interval:
## 3.519434 Inf
## sample estimates:
## mean of x
## 3.758
Deseo contrastar si la variabilidad de la longitud de petalo de la especie setosa es igual a la de la especie versicolor \[ H_0:\sigma^2_{setosa}=\sigma^2_{versicolor}\] \[ H_0:\sigma^2_{setosa}\neq \sigma^2_{versicolor}\]
var.test(iris$Petal.Length[iris$Species=="setosa"], iris$Petal.Length[iris$Species=="versicolor"])
##
## F test to compare two variances
##
## data: iris$Petal.Length[iris$Species == "setosa"] and iris$Petal.Length[iris$Species == "versicolor"]
## F = 0.13658, num df = 49, denom df = 49, p-value = 1.026e-10
## alternative hypothesis: true ratio of variances is not equal to 1
## 95 percent confidence interval:
## 0.07750613 0.24068043
## sample estimates:
## ratio of variances
## 0.1365804
Deseo contrastar si la longitud de petalo de la especie setosa es igual a la de la especie versicolor \[ H_0:\mu_{setosa}=\mu_{versicolor}\] \[ H_0:\mu_{setosa}\neq \mu_{versicolor}\]
t.test(iris$Petal.Length[iris$Species=="setosa"], iris$Petal.Length[iris$Species=="versicolor"], alternative = "two.sided")
##
## Welch Two Sample t-test
##
## data: iris$Petal.Length[iris$Species == "setosa"] and iris$Petal.Length[iris$Species == "versicolor"]
## t = -39.493, df = 62.14, p-value < 2.2e-16
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -2.939618 -2.656382
## sample estimates:
## mean of x mean of y
## 1.462 4.260
Deseo contrastar si la proporción de personas que prefieren una marca X es mas del 80%, se observan 230 personas y de ellas 200 prefieren esa marca. \[ H_0:p\leq 0.8\] \[ H_0:p>0.8\]
binom.test(200, 230, p=0.8, alternative = "greater")
##
## Exact binomial test
##
## data: 200 and 230
## number of successes = 200, number of trials = 230, p-value =
## 0.003841
## alternative hypothesis: true probability of success is greater than 0.8
## 95 percent confidence interval:
## 0.827264 1.000000
## sample estimates:
## probability of success
## 0.8695652
Se desea ver si la longitud de petalo promedio cambia de acuerdo a la especie. Para esto planteo \[ H_0:\mu_1=\mu_2=\mu_3\] \[ H_0:Al\;menos \;un\;par\;diferente\] Para sacar la tabla ANOVA en R se procede
summary(aov(Petal.Length~Species, data=iris))
## Df Sum Sq Mean Sq F value Pr(>F)
## Species 2 437.1 218.55 1180 <2e-16 ***
## Residuals 147 27.2 0.19
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Y como son diferentes, el \(P-valor<2\times 10^{16}\) entonces se realiza la prueba de Tukey,
install.packages("agricolae")
## Installing package into '/home/rstudio-user/R/x86_64-pc-linux-gnu-library/3.6'
## (as 'lib' is unspecified)
library(agricolae)
HSD.test(aov(Petal.Length~Species, data=iris), "Specie", console=T)
##
## Study: aov(Petal.Length ~ Species, data = iris) ~ "Specie"
##
## HSD Test for Petal.Length
##
## Mean Square Error: 0.1851878
##
## Species, means
##
## Petal.Length std r Min Max
## setosa 1.462 0.1736640 50 1.0 1.9
## versicolor 4.260 0.4699110 50 3.0 5.1
## virginica 5.552 0.5518947 50 4.5 6.9
##
## Alpha: 0.05 ; DF Error: 147
## Critical Value of Studentized Range: 3.348424
##
## Minimun Significant Difference: 0.20378
##
## Treatments with the same letter are not significantly different.
##
## Petal.Length groups
## virginica 5.552 a
## versicolor 4.260 b
## setosa 1.462 c
Donde se muestran las medias ordenadas de mayor a menor y las letras de comparación. Virginica es mayor y es diferente de las otras dos (No tienen letras en comun)
En caso de que las dos variables sean categoricas y se quiera probar la hipotesis de independencia, se procede con una prueba \(\chi^2\), por ejemplo, tenemos la tabla de contingencia de Sexo y horario de estudio.
M <- as.table(rbind(c(762, 327, 468), c(484, 239, 477)))
dimnames(M) <- list(genero= c("F", "M"),
Horario= c("Mañana","Tarde", "Noche"))
M
## Horario
## genero Mañana Tarde Noche
## F 762 327 468
## M 484 239 477
Si queremos probar si son independientes,
chisq.test(M)
##
## Pearson's Chi-squared test
##
## data: M
## X-squared = 30.07, df = 2, p-value = 2.954e-07