SESIÓN 1 - CREANDO Y EXPLORANDO DATA FRAMES / EXPLORACIÓN UNIVARIADA

1. Columnas del Data Frame

nombre=c("Jessica", "Raquel", "Carlos", "Manuel", 
         "Alvaro", "Paula", "Gustavo", "Edgar", "Carla")

edad=c(23,20,21,19,
       18,22,23,25,28)

carrera=c("Gestion", "Ciencia Politica", "Economia", "Sociologia", 
          "Antropologia", "Ciencia Politica","Gestion", "Economia", "Sociologia") 

ciudad=c("Lima", "Lima", "Tacna", "Huancayo",
         "Trujillo", "Cusco", "Lima", "Cusco", "Cajamarca")

nota_spss=c(18,9,15,12,
            14,13,19,10,13)

2. Armando el Data Frame

alumnosSpss=data.frame(nombre, 
                       edad, 
                       carrera, 
                       ciudad,
                       nota_spss, 
                       stringsAsFactors = F)

3. Viendo Data Frame

alumnosSpss
##    nombre edad          carrera    ciudad nota_spss
## 1 Jessica   23          Gestion      Lima        18
## 2  Raquel   20 Ciencia Politica      Lima         9
## 3  Carlos   21         Economia     Tacna        15
## 4  Manuel   19       Sociologia  Huancayo        12
## 5  Alvaro   18     Antropologia  Trujillo        14
## 6   Paula   22 Ciencia Politica     Cusco        13
## 7 Gustavo   23          Gestion      Lima        19
## 8   Edgar   25         Economia     Cusco        10
## 9   Carla   28       Sociologia Cajamarca        13

4. Consultas al Data Frame

La data contiene contiene información de alumnos que llevaron un curso de SPSS. Genere el código para responder a las siguientes preguntas:

alumnosSpss[alumnosSpss$nombre=='Manuel',"nota_spss"]
## [1] 12
alumnosSpss[alumnosSpss$edad==max(alumnosSpss$edad),"nombre"]
## [1] "Carla"
alumnosSpss[alumnosSpss$edad==max(alumnosSpss$edad),"carrera"]
## [1] "Sociologia"
alumnosSpss[alumnosSpss$ciudad=='Lima' & alumnosSpss$nota_spss==min(alumnosSpss$nota_spss),"carrera"]
## [1] "Ciencia Politica"

Cree otro data frame:

nombre=c("Maria Fernanda", "Antonella", "Carlos", "Manuel", 
         "Alvaro","Paula","Gustavo", "Edgar","Daniela")

edad=c(23,20,21,19,
       18,22,23,25,28) 
carrera=c("Ciencia Politica", "Ciencia Politica", "Economia", "Sociologia",
          "Antropologia","Ciencia Politica", "Gestion", "Economia", "Sociologia")

ciudad=c("Lima", "Lima", "Tacna", "Huancayo", 
         "Trujillo", "Cusco", "Lima", "Cusco","Cajamarca")

nota_r= c(20,19,15,12,
          13,16,15,11,14)

masculino=c(F,F,T,T,
            T,F,T,T,F)

1. Creando:

alumnosR=data.frame(nombre, edad, carrera, ciudad,nota_r, masculino, 
                    stringsAsFactors = F)

La data contiene contiene información de alumnos que llevaron un curso de R. Muchos de los alumnos que llevaron el curso de SPSS también llevaron el curso de R.

Genere el código para lo siguiente:

alumnosR[order(-nota_r),]
##           nombre edad          carrera    ciudad nota_r masculino
## 1 Maria Fernanda   23 Ciencia Politica      Lima     20     FALSE
## 2      Antonella   20 Ciencia Politica      Lima     19     FALSE
## 6          Paula   22 Ciencia Politica     Cusco     16     FALSE
## 3         Carlos   21         Economia     Tacna     15      TRUE
## 7        Gustavo   23          Gestion      Lima     15      TRUE
## 9        Daniela   28       Sociologia Cajamarca     14     FALSE
## 5         Alvaro   18     Antropologia  Trujillo     13      TRUE
## 4         Manuel   19       Sociologia  Huancayo     12      TRUE
## 8          Edgar   25         Economia     Cusco     11      TRUE

*Ordene alumnos R en base a las carreras (ascendente) y las notas (descendente). Cree un objeto para guardar la data ordenada.

alumnosR_2=alumnosR[order(carrera,-nota_r),]
alumnosR_2
##           nombre edad          carrera    ciudad nota_r masculino
## 5         Alvaro   18     Antropologia  Trujillo     13      TRUE
## 1 Maria Fernanda   23 Ciencia Politica      Lima     20     FALSE
## 2      Antonella   20 Ciencia Politica      Lima     19     FALSE
## 6          Paula   22 Ciencia Politica     Cusco     16     FALSE
## 3         Carlos   21         Economia     Tacna     15      TRUE
## 8          Edgar   25         Economia     Cusco     11      TRUE
## 7        Gustavo   23          Gestion      Lima     15      TRUE
## 9        Daniela   28       Sociologia Cajamarca     14     FALSE
## 4         Manuel   19       Sociologia  Huancayo     12      TRUE
alumnosR[alumnosR$carrera=='Ciencia Politica','nombre']
## [1] "Maria Fernanda" "Antonella"      "Paula"

El comando merge nos permite juntar data frames, añadiendo toda la información (variables) que tenemos disponible sobre los mismos casos. La información completa de nuestros casos puede ser guardada en un nuevo objeto:

alumnos_total = merge(alumnosSpss,alumnosR)
alumnos_total
##    nombre edad          carrera   ciudad nota_spss nota_r masculino
## 1  Alvaro   18     Antropologia Trujillo        14     13      TRUE
## 2  Carlos   21         Economia    Tacna        15     15      TRUE
## 3   Edgar   25         Economia    Cusco        10     11      TRUE
## 4 Gustavo   23          Gestion     Lima        19     15      TRUE
## 5  Manuel   19       Sociologia Huancayo        12     12      TRUE
## 6   Paula   22 Ciencia Politica    Cusco        13     16     FALSE

Genere el código para responder a las siguientes preguntas usando “alumnos_total”:

alumnos_total[alumnos_total$nota_r==max(alumnos_total$nota_r),'nota_spss']
## [1] 13
alumnos_total[(alumnos_total$nota_spss>15) & alumnos_total$nota_r>15,]
## [1] nombre    edad      carrera   ciudad    nota_spss nota_r    masculino
## <0 rows> (or 0-length row.names)

Esto quiere decir que ningun alumno supero la nota de 15 en ambos cursos.

alumnos_total[(alumnos_total$nota_spss==15) & alumnos_total$nota_r==15,'carrera']
## [1] "Economia"

SESIÓN 1 - PRÁCTICA DIRIGIDA

##    Nombre        Partido Edad TAfiliacion Sexo   NivelEdu
## 1    Juan Mundo Colorado   45          11    M secundaria
## 2   Rocio     Los Verdes   42           3    F  bachiller
## 3  Manuel     Los Tibios   34           2    M  bachiller
## 4   Pedro Mundo Colorado   41           9    M  bachiller
## 5   Carla     Los Tibios   25           3    F  bachiller
## 6  Fresia     Los Verdes   24           2    F  bachiller
## 7 Alfredo     Los Verdes   30           2    M   magister
## 8  Teresa     Los Verdes   35          12    F  bachiller
## 9   Maria     Los Tibios   37           7    F  bachiller
  1. El mayor del grupo es:
##   Nombre        Partido Edad TAfiliacion Sexo   NivelEdu
## 1   Juan Mundo Colorado   45          11    M secundaria
  1. El sexo del menor del grupo es:
## [1] "F"
  1. El partido de Fresia es:
## [1] "Los Verdes"
  1. El nivel educativo y nombre de la persona con mas años de afiliacion es:
##   Nombre  NivelEdu
## 8 Teresa bachiller
  1. El nombre de las mujeres del partido Los Verdes:
## [1] "Rocio"  "Fresia" "Teresa"
  1. La edad y nombre de la persona con mayor tiempo de afiliacion en el partido Los Verdes:
##   Nombre Edad
## 8 Teresa   35

SESIÓN 2 - EXPLORACIÓN CATEGÓRICA Y RECODIFICACIÓN

linkCSV="https://docs.google.com/spreadsheets/d/e/2PACX-1vQjaIOfcqt963uYbmuShDtt5bBcXTUdL33NA1cItQfH2vZICi5S6QtfJjILY1uxYSJf2GUSzduA0iZZ/pub?gid=1795242876&single=true&output=csv"

Alumnos=read.csv(linkCSV, stringsAsFactors = F, na.strings = '')
names(Alumnos)
##  [1] "ID"     "SEX"    "RACE"   "SES"    "SCTYP"  "LOCUS"  "CONCPT"
##  [8] "MOT"    "RDG"    "WRTG"   "MATH"   "SCI"    "CIV"

Sirve para identificar variables ordinales y variables nominales

str(Alumnos)
## 'data.frame':    600 obs. of  13 variables:
##  $ ID    : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ SEX   : chr  "HOMBRE" "MUJER" "HOMBRE" "HOMBRE" ...
##  $ RACE  : chr  "ASIATICO" "ASIATICO" "ASIATICO" "ASIATICO" ...
##  $ SES   : chr  "ALTO" "ALTO" "ALTO" "MEDIO" ...
##  $ SCTYP : chr  "PUBLICA" "PUBLICA" "PUBLICA" "PUBLICA" ...
##  $ LOCUS : num  0.29 -0.42 0.71 0.06 0.22 0.46 0.44 0.68 0.06 0.05 ...
##  $ CONCPT: num  0.88 0.03 0.03 0.03 -0.28 0.03 -0.47 0.25 0.56 0.15 ...
##  $ MOT   : num  0.67 0.33 0.67 0 0 0 0.33 1 0.33 1 ...
##  $ RDG   : num  33.6 46.9 41.6 38.9 36.3 49.5 62.7 44.2 46.9 44.2 ...
##  $ WRTG  : num  43.7 35.9 59.3 41.1 48.9 46.3 64.5 51.5 41.1 49.5 ...
##  $ MATH  : num  40.2 41.9 41.9 32.7 39.5 46.2 48 36.9 45.3 40.5 ...
##  $ SCI   : num  39 36.3 44.4 41.7 41.7 41.7 63.4 49.8 47.1 39 ...
##  $ CIV   : num  40.6 45.6 45.6 40.6 45.6 35.6 55.6 55.6 55.6 50.6 ...

Explorar la categorica, sobre todo como variable dependiente, significa querer saber:

summary(Alumnos)
##        ID            SEX                RACE               SES           
##  Min.   :  1.0   Length:600         Length:600         Length:600        
##  1st Qu.:150.8   Class :character   Class :character   Class :character  
##  Median :300.5   Mode  :character   Mode  :character   Mode  :character  
##  Mean   :300.5                                                           
##  3rd Qu.:450.2                                                           
##  Max.   :600.0                                                           
##     SCTYP               LOCUS              CONCPT         
##  Length:600         Min.   :-2.23000   Min.   :-2.620000  
##  Class :character   1st Qu.:-0.37250   1st Qu.:-0.300000  
##  Mode  :character   Median : 0.21000   Median : 0.030000  
##                     Mean   : 0.09653   Mean   : 0.004917  
##                     3rd Qu.: 0.51000   3rd Qu.: 0.440000  
##                     Max.   : 1.36000   Max.   : 1.190000  
##       MOT              RDG            WRTG            MATH      
##  Min.   :0.0000   Min.   :28.3   Min.   :25.50   Min.   :31.80  
##  1st Qu.:0.3300   1st Qu.:44.2   1st Qu.:44.30   1st Qu.:44.50  
##  Median :0.6700   Median :52.1   Median :54.10   Median :51.30  
##  Mean   :0.6608   Mean   :51.9   Mean   :52.38   Mean   :51.85  
##  3rd Qu.:1.0000   3rd Qu.:60.1   3rd Qu.:59.90   3rd Qu.:58.38  
##  Max.   :1.0000   Max.   :76.0   Max.   :67.10   Max.   :75.50  
##       SCI             CIV       
##  Min.   :26.00   Min.   :25.70  
##  1st Qu.:44.40   1st Qu.:45.60  
##  Median :52.60   Median :50.60  
##  Mean   :51.76   Mean   :52.05  
##  3rd Qu.:58.65   3rd Qu.:60.50  
##  Max.   :74.20   Max.   :70.50

EXPLORANDO VARIABLES NOMINALES

table(Alumnos$SES)
## 
##  ALTO  BAJO MEDIO 
##   139   162   299

TABLA DE FRECUENCIAS AVANZADA

library(questionr)
library(magrittr)

DataSES=freq(Alumnos$SES,total = F,sort = 'dec',exclude = c(NA)) %>% data.frame()
DataSES=data.frame(variable=row.names(DataSES),DataSES,row.names = NULL)

DataSES
##   variable   n   X.
## 1    MEDIO 299 49.8
## 2     BAJO 162 27.0
## 3     ALTO 139 23.2
library(ggplot2)

# en base solo se pone: en data como se llama la tabla de frecuencias
# y en aes la variable 'x' para los nombres y la 'y' para los conteos.

base = ggplot(data = DataSES,aes(x=variable,y=n))
barSES = base + geom_bar(stat = 'identity')

# luego a la base se le pide añadir la 'geometria' deseada:

barSES

* Gráfico según orden de la tabla

barSES = barSES + scale_x_discrete(limits = DataSES$variable)

barSES

text1="¿Qué SES es más común entre los estudiantes?"
text2="Condición económico-social (SES)"
text3="Estudiantes"
text4="Fuente:National Center for Education Statistcs"

barSES2 = barSES + labs(title = text1,
                   x = text2,
                   y = text3,
                   caption = text4)

barSES2

barSES2 + theme_classic() + 
            theme(plot.title = element_text(hjust = 0.5,size=15), # centrar y agrandar
                  plot.caption = element_text(hjust = 0), # a la derecha
                  axis.text.x = element_text(angle=45,hjust = 1)) # angulo

Se realiza en función del 80% de consecuencias causadas por el 20% de los problemas. Muestra dos medidas, los conteos y los porcentajes acumulados.El gráfico de Pareto muestra dos medidas, los conteos y los porcentajes acumulados. Por tradición se trata de detectar que valores representan el 80%.

library(qcc)
## Package 'qcc' version 2.7
## Type 'citation("qcc")' for citing this R package in publications.
pareto.chart(table(Alumnos$SES),cumperc = c(0,50,80,100))

##        
## Pareto chart analysis for table(Alumnos$SES)
##         Frequency Cum.Freq. Percentage Cum.Percent.
##   MEDIO 299.00000 299.00000   49.83333     49.83333
##   BAJO  162.00000 461.00000   27.00000     76.83333
##   ALTO  139.00000 600.00000   23.16667    100.00000

Las acciones de conminar y de patrullaje son casi el 80% de las actividades de serenazgo de San Isidro.

library(DescTools)
Mode(Alumnos$SES)
## [1] "MEDIO"
dataTable=table(Alumnos$SES)
Herfindahl(dataTable)
## [1] 0.3749056
# * < 0.01 : indica que la moda no es significativa, las categorias tienen pesos similares.
# * < 0.15 : indica que la moda no es significativa, varias categorias tienen pesos similares.
# * entre 0.15 - 0.3: hay una moda.
# * > 0.3: La moda se diferencia de los demas
1/sum(prop.table(dataTable)**2)
## [1] 2.667338

Variables ORDINALES

table(Alumnos$LOCUS)
## 
## -2.23 -1.99 -1.81 -1.78 -1.76 -1.74 -1.58 -1.57 -1.56 -1.55  -1.5 -1.34 
##     2     1     1     2     1     1     2     1     1     1     1     1 
## -1.33  -1.3 -1.28 -1.15 -1.14 -1.13  -1.1 -1.09 -1.06 -1.05 -1.02 -0.93 
##     9     2     3     2     1     1     3     3     1     3     1     3 
## -0.91  -0.9 -0.89 -0.88 -0.86 -0.84 -0.83 -0.82  -0.8 -0.71 -0.69 -0.68 
##     1     2     4     1     2     7     3     2     1     1     1     3 
## -0.67 -0.66 -0.65 -0.64 -0.63 -0.61  -0.6 -0.59 -0.54 -0.51 -0.49 -0.47 
##     1     3     2     2     1     3     9     3     1     1     2     2 
## -0.45 -0.44 -0.43 -0.42 -0.41  -0.4 -0.39 -0.38 -0.37 -0.36 -0.35 -0.34 
##     3    10     3     2     3    14     2     8     2     1     1     1 
## -0.33 -0.27 -0.24 -0.23 -0.22 -0.21  -0.2 -0.19 -0.18 -0.17 -0.16 -0.14 
##     1     2     2     2     3     3     1     7     4     3     7     7 
## -0.11 -0.04 -0.03     0  0.01  0.02  0.03  0.04  0.05  0.06  0.07  0.08 
##     1     2     3    15     1     9     4     2     3    41     1     5 
##  0.09   0.1  0.11   0.2  0.21  0.22  0.23  0.24  0.25  0.26  0.27  0.28 
##     1     7     1     6     2     9     9     2     5    12     6     7 
##  0.29   0.3  0.31  0.32  0.33  0.42  0.43  0.44  0.45  0.46  0.47  0.48 
##     3     5     4     7     2     2     3     5     7    41     5     7 
##  0.49   0.5  0.51  0.52  0.53  0.55  0.57  0.65  0.66  0.67  0.68  0.69 
##     4     2     3     8     1     5     1     1     9     2    18     3 
##   0.7  0.71  0.73  0.75  0.87  0.89  0.91  0.93  0.94  0.96  1.11  1.12 
##     3    17     3     6     1     6    12     4     2     4     6     1 
##  1.13  1.14  1.16  1.36 
##    10     2    11    13
DataLocus=freq(Alumnos$LOCUS,total = F,exclude = c(NA)) %>% data.frame()
DataLocus=data.frame(variable=row.names(DataLocus),DataLocus,row.names = NULL)

DataLocus
##     variable  n  X.
## 1      -2.23  2 0.3
## 2      -1.99  1 0.2
## 3      -1.81  1 0.2
## 4      -1.78  2 0.3
## 5      -1.76  1 0.2
## 6      -1.74  1 0.2
## 7      -1.58  2 0.3
## 8      -1.57  1 0.2
## 9      -1.56  1 0.2
## 10     -1.55  1 0.2
## 11      -1.5  1 0.2
## 12     -1.34  1 0.2
## 13     -1.33  9 1.5
## 14      -1.3  2 0.3
## 15     -1.28  3 0.5
## 16     -1.15  2 0.3
## 17     -1.14  1 0.2
## 18     -1.13  1 0.2
## 19      -1.1  3 0.5
## 20     -1.09  3 0.5
## 21     -1.06  1 0.2
## 22     -1.05  3 0.5
## 23     -1.02  1 0.2
## 24     -0.93  3 0.5
## 25     -0.91  1 0.2
## 26      -0.9  2 0.3
## 27     -0.89  4 0.7
## 28     -0.88  1 0.2
## 29     -0.86  2 0.3
## 30     -0.84  7 1.2
## 31     -0.83  3 0.5
## 32     -0.82  2 0.3
## 33      -0.8  1 0.2
## 34     -0.71  1 0.2
## 35     -0.69  1 0.2
## 36     -0.68  3 0.5
## 37     -0.67  1 0.2
## 38     -0.66  3 0.5
## 39     -0.65  2 0.3
## 40     -0.64  2 0.3
## 41     -0.63  1 0.2
## 42     -0.61  3 0.5
## 43      -0.6  9 1.5
## 44     -0.59  3 0.5
## 45     -0.54  1 0.2
## 46     -0.51  1 0.2
## 47     -0.49  2 0.3
## 48     -0.47  2 0.3
## 49     -0.45  3 0.5
## 50     -0.44 10 1.7
## 51     -0.43  3 0.5
## 52     -0.42  2 0.3
## 53     -0.41  3 0.5
## 54      -0.4 14 2.3
## 55     -0.39  2 0.3
## 56     -0.38  8 1.3
## 57     -0.37  2 0.3
## 58     -0.36  1 0.2
## 59     -0.35  1 0.2
## 60     -0.34  1 0.2
## 61     -0.33  1 0.2
## 62     -0.27  2 0.3
## 63     -0.24  2 0.3
## 64     -0.23  2 0.3
## 65     -0.22  3 0.5
## 66     -0.21  3 0.5
## 67      -0.2  1 0.2
## 68     -0.19  7 1.2
## 69     -0.18  4 0.7
## 70     -0.17  3 0.5
## 71     -0.16  7 1.2
## 72     -0.14  7 1.2
## 73     -0.11  1 0.2
## 74     -0.04  2 0.3
## 75     -0.03  3 0.5
## 76         0 15 2.5
## 77      0.01  1 0.2
## 78      0.02  9 1.5
## 79      0.03  4 0.7
## 80      0.04  2 0.3
## 81      0.05  3 0.5
## 82      0.06 41 6.8
## 83      0.07  1 0.2
## 84      0.08  5 0.8
## 85      0.09  1 0.2
## 86       0.1  7 1.2
## 87      0.11  1 0.2
## 88       0.2  6 1.0
## 89      0.21  2 0.3
## 90      0.22  9 1.5
## 91      0.23  9 1.5
## 92      0.24  2 0.3
## 93      0.25  5 0.8
## 94      0.26 12 2.0
## 95      0.27  6 1.0
## 96      0.28  7 1.2
## 97      0.29  3 0.5
## 98       0.3  5 0.8
## 99      0.31  4 0.7
## 100     0.32  7 1.2
## 101     0.33  2 0.3
## 102     0.42  2 0.3
## 103     0.43  3 0.5
## 104     0.44  5 0.8
## 105     0.45  7 1.2
## 106     0.46 41 6.8
## 107     0.47  5 0.8
## 108     0.48  7 1.2
## 109     0.49  4 0.7
## 110      0.5  2 0.3
## 111     0.51  3 0.5
## 112     0.52  8 1.3
## 113     0.53  1 0.2
## 114     0.55  5 0.8
## 115     0.57  1 0.2
## 116     0.65  1 0.2
## 117     0.66  9 1.5
## 118     0.67  2 0.3
## 119     0.68 18 3.0
## 120     0.69  3 0.5
## 121      0.7  3 0.5
## 122     0.71 17 2.8
## 123     0.73  3 0.5
## 124     0.75  6 1.0
## 125     0.87  1 0.2
## 126     0.89  6 1.0
## 127     0.91 12 2.0
## 128     0.93  4 0.7
## 129     0.94  2 0.3
## 130     0.96  4 0.7
## 131     1.11  6 1.0
## 132     1.12  1 0.2
## 133     1.13 10 1.7
## 134     1.14  2 0.3
## 135     1.16 11 1.8
## 136     1.36 13 2.2
base=ggplot(data = DataLocus, aes(x=variable, y=n))

barLOCUS= base + geom_bar(stat = 'identity')

barLOCUS

pareto.chart(table(Alumnos$LOCUS),cumperc = c(0,50,80,100))

##        
## Pareto chart analysis for table(Alumnos$LOCUS)
##           Frequency   Cum.Freq.  Percentage Cum.Percent.
##   0.06   41.0000000  41.0000000   6.8333333    6.8333333
##   0.46   41.0000000  82.0000000   6.8333333   13.6666667
##   0.68   18.0000000 100.0000000   3.0000000   16.6666667
##   0.71   17.0000000 117.0000000   2.8333333   19.5000000
##   0      15.0000000 132.0000000   2.5000000   22.0000000
##   -0.4   14.0000000 146.0000000   2.3333333   24.3333333
##   1.36   13.0000000 159.0000000   2.1666667   26.5000000
##   0.26   12.0000000 171.0000000   2.0000000   28.5000000
##   0.91   12.0000000 183.0000000   2.0000000   30.5000000
##   1.16   11.0000000 194.0000000   1.8333333   32.3333333
##   -0.44  10.0000000 204.0000000   1.6666667   34.0000000
##   1.13   10.0000000 214.0000000   1.6666667   35.6666667
##   -1.33   9.0000000 223.0000000   1.5000000   37.1666667
##   -0.6    9.0000000 232.0000000   1.5000000   38.6666667
##   0.02    9.0000000 241.0000000   1.5000000   40.1666667
##   0.22    9.0000000 250.0000000   1.5000000   41.6666667
##   0.23    9.0000000 259.0000000   1.5000000   43.1666667
##   0.66    9.0000000 268.0000000   1.5000000   44.6666667
##   -0.38   8.0000000 276.0000000   1.3333333   46.0000000
##   0.52    8.0000000 284.0000000   1.3333333   47.3333333
##   -0.84   7.0000000 291.0000000   1.1666667   48.5000000
##   -0.19   7.0000000 298.0000000   1.1666667   49.6666667
##   -0.16   7.0000000 305.0000000   1.1666667   50.8333333
##   -0.14   7.0000000 312.0000000   1.1666667   52.0000000
##   0.1     7.0000000 319.0000000   1.1666667   53.1666667
##   0.28    7.0000000 326.0000000   1.1666667   54.3333333
##   0.32    7.0000000 333.0000000   1.1666667   55.5000000
##   0.45    7.0000000 340.0000000   1.1666667   56.6666667
##   0.48    7.0000000 347.0000000   1.1666667   57.8333333
##   0.2     6.0000000 353.0000000   1.0000000   58.8333333
##   0.27    6.0000000 359.0000000   1.0000000   59.8333333
##   0.75    6.0000000 365.0000000   1.0000000   60.8333333
##   0.89    6.0000000 371.0000000   1.0000000   61.8333333
##   1.11    6.0000000 377.0000000   1.0000000   62.8333333
##   0.08    5.0000000 382.0000000   0.8333333   63.6666667
##   0.25    5.0000000 387.0000000   0.8333333   64.5000000
##   0.3     5.0000000 392.0000000   0.8333333   65.3333333
##   0.44    5.0000000 397.0000000   0.8333333   66.1666667
##   0.47    5.0000000 402.0000000   0.8333333   67.0000000
##   0.55    5.0000000 407.0000000   0.8333333   67.8333333
##   -0.89   4.0000000 411.0000000   0.6666667   68.5000000
##   -0.18   4.0000000 415.0000000   0.6666667   69.1666667
##   0.03    4.0000000 419.0000000   0.6666667   69.8333333
##   0.31    4.0000000 423.0000000   0.6666667   70.5000000
##   0.49    4.0000000 427.0000000   0.6666667   71.1666667
##   0.93    4.0000000 431.0000000   0.6666667   71.8333333
##   0.96    4.0000000 435.0000000   0.6666667   72.5000000
##   -1.28   3.0000000 438.0000000   0.5000000   73.0000000
##   -1.1    3.0000000 441.0000000   0.5000000   73.5000000
##   -1.09   3.0000000 444.0000000   0.5000000   74.0000000
##   -1.05   3.0000000 447.0000000   0.5000000   74.5000000
##   -0.93   3.0000000 450.0000000   0.5000000   75.0000000
##   -0.83   3.0000000 453.0000000   0.5000000   75.5000000
##   -0.68   3.0000000 456.0000000   0.5000000   76.0000000
##   -0.66   3.0000000 459.0000000   0.5000000   76.5000000
##   -0.61   3.0000000 462.0000000   0.5000000   77.0000000
##   -0.59   3.0000000 465.0000000   0.5000000   77.5000000
##   -0.45   3.0000000 468.0000000   0.5000000   78.0000000
##   -0.43   3.0000000 471.0000000   0.5000000   78.5000000
##   -0.41   3.0000000 474.0000000   0.5000000   79.0000000
##   -0.22   3.0000000 477.0000000   0.5000000   79.5000000
##   -0.21   3.0000000 480.0000000   0.5000000   80.0000000
##   -0.17   3.0000000 483.0000000   0.5000000   80.5000000
##   -0.03   3.0000000 486.0000000   0.5000000   81.0000000
##   0.05    3.0000000 489.0000000   0.5000000   81.5000000
##   0.29    3.0000000 492.0000000   0.5000000   82.0000000
##   0.43    3.0000000 495.0000000   0.5000000   82.5000000
##   0.51    3.0000000 498.0000000   0.5000000   83.0000000
##   0.69    3.0000000 501.0000000   0.5000000   83.5000000
##   0.7     3.0000000 504.0000000   0.5000000   84.0000000
##   0.73    3.0000000 507.0000000   0.5000000   84.5000000
##   -2.23   2.0000000 509.0000000   0.3333333   84.8333333
##   -1.78   2.0000000 511.0000000   0.3333333   85.1666667
##   -1.58   2.0000000 513.0000000   0.3333333   85.5000000
##   -1.3    2.0000000 515.0000000   0.3333333   85.8333333
##   -1.15   2.0000000 517.0000000   0.3333333   86.1666667
##   -0.9    2.0000000 519.0000000   0.3333333   86.5000000
##   -0.86   2.0000000 521.0000000   0.3333333   86.8333333
##   -0.82   2.0000000 523.0000000   0.3333333   87.1666667
##   -0.65   2.0000000 525.0000000   0.3333333   87.5000000
##   -0.64   2.0000000 527.0000000   0.3333333   87.8333333
##   -0.49   2.0000000 529.0000000   0.3333333   88.1666667
##   -0.47   2.0000000 531.0000000   0.3333333   88.5000000
##   -0.42   2.0000000 533.0000000   0.3333333   88.8333333
##   -0.39   2.0000000 535.0000000   0.3333333   89.1666667
##   -0.37   2.0000000 537.0000000   0.3333333   89.5000000
##   -0.27   2.0000000 539.0000000   0.3333333   89.8333333
##   -0.24   2.0000000 541.0000000   0.3333333   90.1666667
##   -0.23   2.0000000 543.0000000   0.3333333   90.5000000
##   -0.04   2.0000000 545.0000000   0.3333333   90.8333333
##   0.04    2.0000000 547.0000000   0.3333333   91.1666667
##   0.21    2.0000000 549.0000000   0.3333333   91.5000000
##   0.24    2.0000000 551.0000000   0.3333333   91.8333333
##   0.33    2.0000000 553.0000000   0.3333333   92.1666667
##   0.42    2.0000000 555.0000000   0.3333333   92.5000000
##   0.5     2.0000000 557.0000000   0.3333333   92.8333333
##   0.67    2.0000000 559.0000000   0.3333333   93.1666667
##   0.94    2.0000000 561.0000000   0.3333333   93.5000000
##   1.14    2.0000000 563.0000000   0.3333333   93.8333333
##   -1.99   1.0000000 564.0000000   0.1666667   94.0000000
##   -1.81   1.0000000 565.0000000   0.1666667   94.1666667
##   -1.76   1.0000000 566.0000000   0.1666667   94.3333333
##   -1.74   1.0000000 567.0000000   0.1666667   94.5000000
##   -1.57   1.0000000 568.0000000   0.1666667   94.6666667
##   -1.56   1.0000000 569.0000000   0.1666667   94.8333333
##   -1.55   1.0000000 570.0000000   0.1666667   95.0000000
##   -1.5    1.0000000 571.0000000   0.1666667   95.1666667
##   -1.34   1.0000000 572.0000000   0.1666667   95.3333333
##   -1.14   1.0000000 573.0000000   0.1666667   95.5000000
##   -1.13   1.0000000 574.0000000   0.1666667   95.6666667
##   -1.06   1.0000000 575.0000000   0.1666667   95.8333333
##   -1.02   1.0000000 576.0000000   0.1666667   96.0000000
##   -0.91   1.0000000 577.0000000   0.1666667   96.1666667
##   -0.88   1.0000000 578.0000000   0.1666667   96.3333333
##   -0.8    1.0000000 579.0000000   0.1666667   96.5000000
##   -0.71   1.0000000 580.0000000   0.1666667   96.6666667
##   -0.69   1.0000000 581.0000000   0.1666667   96.8333333
##   -0.67   1.0000000 582.0000000   0.1666667   97.0000000
##   -0.63   1.0000000 583.0000000   0.1666667   97.1666667
##   -0.54   1.0000000 584.0000000   0.1666667   97.3333333
##   -0.51   1.0000000 585.0000000   0.1666667   97.5000000
##   -0.36   1.0000000 586.0000000   0.1666667   97.6666667
##   -0.35   1.0000000 587.0000000   0.1666667   97.8333333
##   -0.34   1.0000000 588.0000000   0.1666667   98.0000000
##   -0.33   1.0000000 589.0000000   0.1666667   98.1666667
##   -0.2    1.0000000 590.0000000   0.1666667   98.3333333
##   -0.11   1.0000000 591.0000000   0.1666667   98.5000000
##   0.01    1.0000000 592.0000000   0.1666667   98.6666667
##   0.07    1.0000000 593.0000000   0.1666667   98.8333333
##   0.09    1.0000000 594.0000000   0.1666667   99.0000000
##   0.11    1.0000000 595.0000000   0.1666667   99.1666667
##   0.53    1.0000000 596.0000000   0.1666667   99.3333333
##   0.57    1.0000000 597.0000000   0.1666667   99.5000000
##   0.65    1.0000000 598.0000000   0.1666667   99.6666667
##   0.87    1.0000000 599.0000000   0.1666667   99.8333333
##   1.12    1.0000000 600.0000000   0.1666667  100.0000000
library(DescTools)
Mode(Alumnos$LOCUS)
## [1] 0.06 0.46
dataTable=table(Alumnos$LOCUS)

Herfindahl(dataTable)
## [1] 0.01954444
1/sum(prop.table(dataTable)**2)
## [1] 51.16543
Median(Alumnos$LOCUS)
## [1] 0.21

En la ordinal ya se puede pedir mediana. La mediana indica hasta qué valor llega el 50% de los valores que han tomado los datos.

ggplot(Alumnos,aes(y=LOCUS)) + geom_boxplot() + scale_y_discrete(limits=DataLocus$variable) 

Note los valores 3, 4 y 6.

El 3 es el primer cuartil: 25% de las acciones de los serenos se dan de domingo a miercoles. El 4 es la mediana o cuartil 2. El 6 es el cuartil 3: Otro 25% de las acciones de los serenos se dan de viernes a sábado.

SESIÓN 3 - TABLAS DESDE LA WEB

  1. Leer datos.
library(htmltab)

# PARA TRABAJAR CON VARIAS TABLAS DE UN MISMO LINK

LINKGUERRAS = "https://en.wikipedia.org/wiki/List_of_wars_by_death_toll" 

ancient = htmltab(doc = LINKGUERRAS, 
               which ='//*[@id="mw-content-text"]/div/table[4]') # aqui va XPATH

medieval = htmltab(doc = LINKGUERRAS, 
               which ='//*[@id="mw-content-text"]/div/table[6]') # aqui va XPATH
## Warning: Columns [Notes] seem to have no data and are removed. Use
## rm_nodata_cols = F to suppress this behavior
modern = htmltab(doc = LINKGUERRAS, 
               which ='//*[@id="mw-content-text"]/div/table[7]') # aqui va XPATH
## Warning: Columns [Notes] seem to have no data and are removed. Use
## rm_nodata_cols = F to suppress this behavior
  1. Identificando nombres de variables
names(ancient)
## [1] "War"                   "Deathrange"            "Geometricmean(Note 1)"
## [4] "Date"                  "Combatants"            "Location"             
## [7] "Notes"
names(medieval)
## [1] "War"           "Deathrange"    "Geometricmean" "Date"         
## [5] "Combatants"    "Location"
names(modern)
## [1] "War"           "Deathrange"    "Geometricmean" "Date"         
## [5] "Combatants"    "Location"
  1. Creando subconjuntos

Quieres combinar los tres en uno solo. Eso se puede hacer si todas las columnas tienen nombres identicos. Quedate con estas columnas:

guerras1=ancient[,c("War","Location")]
guerras2=medieval[,c("War","Location")]
guerras3=modern[,c("War","Location")]

guerras=rbind(guerras1,guerras2,guerras3) #Usa la funcion rbind para poner las tablas una debajo de la otra

str(guerras)
## 'data.frame':    162 obs. of  2 variables:
##  $ War     : chr  "Conquests of Cyrus the Great" "Greco–Persian Wars" "Samnite Wars" "Wars of Alexander the Great" ...
##  $ Location: chr  "Middle East" "Greece" "Italy" "Middle East / North Africa / Central Asia / India" ...

Cada data frame tiene ahora 2 columnas cada uno.

  1. Análisis estadístico - Location
table(guerras$Location)
## 
##                                       Afghanistan 
##                                                 3 
##                                           Algeria 
##                                                 3 
##                                          Americas 
##                                                 1 
##                                            Angola 
##                                                 2 
##                                  Balkan Peninsula 
##                                                 1 
##                                        Bangladesh 
##                                                 1 
##                                            Bosnia 
##                                                 1 
##                                     British Isles 
##                                                 1 
##                                           Burundi 
##                                                 1 
##                                   Caucasus region 
##                                                 1 
##                                    Central Africa 
##                                                 2 
##                                             China 
##                                                 9 
##                                  China /  Vietnam 
##                                                 1 
##                                          Colombia 
##                                                 3 
##                                             Congo 
##                                                 4 
##                                 Crimean Peninsula 
##                                                 1 
##                                              Cuba 
##                                                 2 
##                                         East Asia 
##                                                 1 
##                                    Eastern Europe 
##                                                 4 
##       Eastern Europe / Middle East / North Africa 
##                                                 1 
##                                           England 
##                                                 2 
##                                   England / Wales 
##                                                 1 
##                                          Ethiopia 
##                                                 2 
##                                           Eurasia 
##                                                 2 
##                                            Europe 
##                                                 4 
##                                 Europe / Americas 
##                                                 2 
##                Europe / Middle East ("Holy Land") 
##                                                 1 
##                                           Finland 
##                                                 1 
##                                            France 
##                                                 3 
##                                           Germany 
##                                                 1 
##                                            Greece 
##                                                 2 
##                                             Haiti 
##                                                 1 
##                                 Iberian Peninsula 
##                                                 1 
##                                             India 
##                                                 4 
##                                  India-Bangladesh 
##                                                 1 
##                                         Indonesia 
##                                                 1 
##                                              Iraq 
##                                                 5 
##                                             Italy 
##                                                 1 
##                                             Korea 
##                                                 3 
##                                              Laos 
##                                                 1 
##                                           Lebanon 
##                                                 1 
##                                             Libya 
##                                                 1 
##                                        Madagascar 
##                                                 1 
##                                         Manchuria 
##                                                 1 
##                                            Mexico 
##                                                 4 
##                                       Middle East 
##                                                 7 
##                        Middle East / North Africa 
##                                                 1 
## Middle East / North Africa / Central Asia / India 
##                                                 1 
##      Middle East / North Africa / Southern Europe 
##                                                 1 
##                          Middle East/North Africa 
##                                                 1 
##                                        Mozambique 
##                                                 1 
##                                           Myanmar 
##                                                 1 
##                                        New Guinea 
##                                                 1 
##                                           Nigeria 
##                                                 2 
##                                      North Africa 
##                                                 1 
##                                     North America 
##                                                 1 
##                            North India / Pakistan 
##                                                 1 
##                                   Northeast India 
##                                                 2 
##                                    Northern China 
##                                                 1 
##                                   Northern Europe 
##                                                 1 
##                                          Pakistan 
##                                                 1 
##                                         Patagonia 
##                                                 1 
##                                              Peru 
##                                                 2 
##                                       Philippines 
##                                                 3 
##                                            Russia 
##                                                 2 
##                                            Rwanda 
##                                                 1 
##                                Scotland / England 
##                                                 1 
##                                      Sierra Leone 
##                                                 1 
##                                           Somalia 
##                                                 1 
##                                      South Africa 
##                                                 1 
##                                     South America 
##                                                 1 
##                                    Southeast Asia 
##                                                 2 
##                                  Southeast Europe 
##                                                 1 
##                                   Southern Africa 
##                                                 1 
##                                   Southern Europe 
##                                                 1 
##                    Southern Europe / North Africa 
##                                                 2 
##                                             Spain 
##                                                 2 
##                                         Sri Lanka 
##                                                 1 
##                                             Sudan 
##                                                 3 
##                                             Syria 
##                                                 1 
##                                           Tunisia 
##                                                 1 
##                                            Uganda 
##                                                 1 
##                                               USA 
##                                                 1 
##                                         Venezuela 
##                                                 1 
##                                           Vietnam 
##                                                 1 
##                                    Western Europe 
##                                                 4 
##                     Western Europe / North Africa 
##                                                 2 
##                                         Worldwide 
##                                                 7 
##                                             Yemen 
##                                                 2

también

library(knitr)
dataTable=table(guerras$Location) #ASÍ LUCE MEJOR
kable(dataTable)
Var1 Freq
Afghanistan 3
Algeria 3
Americas 1
Angola 2
Balkan Peninsula 1
Bangladesh 1
Bosnia 1
British Isles 1
Burundi 1
Caucasus region 1
Central Africa 2
China 9
China / Vietnam 1
Colombia 3
Congo 4
Crimean Peninsula 1
Cuba 2
East Asia 1
Eastern Europe 4
Eastern Europe / Middle East / North Africa 1
England 2
England / Wales 1
Ethiopia 2
Eurasia 2
Europe 4
Europe / Americas 2
Europe / Middle East (“Holy Land”) 1
Finland 1
France 3
Germany 1
Greece 2
Haiti 1
Iberian Peninsula 1
India 4
India-Bangladesh 1
Indonesia 1
Iraq 5
Italy 1
Korea 3
Laos 1
Lebanon 1
Libya 1
Madagascar 1
Manchuria 1
Mexico 4
Middle East 7
Middle East / North Africa 1
Middle East / North Africa / Central Asia / India 1
Middle East / North Africa / Southern Europe 1
Middle East/North Africa 1
Mozambique 1
Myanmar 1
New Guinea 1
Nigeria 2
North Africa 1
North America 1
North India / Pakistan 1
Northeast India 2
Northern China 1
Northern Europe 1
Pakistan 1
Patagonia 1
Peru 2
Philippines 3
Russia 2
Rwanda 1
Scotland / England 1
Sierra Leone 1
Somalia 1
South Africa 1
South America 1
Southeast Asia 2
Southeast Europe 1
Southern Africa 1
Southern Europe 1
Southern Europe / North Africa 2
Spain 2
Sri Lanka 1
Sudan 3
Syria 1
Tunisia 1
Uganda 1
USA 1
Venezuela 1
Vietnam 1
Western Europe 4
Western Europe / North Africa 2
Worldwide 7
Yemen 2
  1. Gráficos
library(ggplot2)
base = ggplot(data=guerras,aes(x=Location)) #básico
bar1 = base + geom_bar()
bar1 

Con títulos

bar1 = bar1 + labs(x="Pais/zona", 
                   y="Cantidad",
                  title="Ubicacion de las Guerras en la historia", 
                  subtitle = "Solo con mas 25000 muertos",
                  caption = "Fuente: Wikipedia")

bar1

Datos en ángulo

bar1 + theme(axis.text.x = element_text(angle = 90,size=6,hjust = 1))

  1. Estadísticos
library(DescTools)
Mode(guerras$Location)
## [1] "China"
library(DescTools)
Herfindahl(dataTable)
## [1] 0.01851852
1/Herfindahl(dataTable)
## [1] 54

Hay 54 locaciones importantes de 89.

PRÁCTICA CALIFICADA - TABLAS WEB

TABLAS:

En los dos casos planteados, se está trabajando con variables nominales.

TABLA MASCULINO

  1. TABLA DE DATOS
library(htmltab)

linkPage='https://en.wikipedia.org/wiki/List_of_Wimbledon_gentlemen%27s_singles_champions'
linkTabla='//*[@id="mw-content-text"]/div/table[4]/tbody'
OpenEra=htmltab(doc = linkPage, which = linkTabla)

OpenEra=OpenEra[c(2)]
names(OpenEra)
## [1] "Country"
str(OpenEra)
## 'data.frame':    52 obs. of  1 variable:
##  $ Country: chr  " AUS" " AUS" " AUS" " AUS" ...
head(OpenEra)
##   Country
## 2     AUS
## 3     AUS
## 4     AUS
## 5     AUS
## 6     USA
## 7     TCH

2.GRÁFICOS

library(questionr)
library(magrittr) 

freqCountry=freq(OpenEra$Country,cum = T)%>%data.frame()
freqCountry=data.frame(Country=row.names(freqCountry),freqCountry,row.names = NULL)

freqCountry
##    Country  n   X. val. X.cum val.cum
## 1      SUI  8 15.4 15.4  15.4    15.4
## 2      AUS  6 11.5 11.5  26.9    26.9
## 3      CRO  1  1.9  1.9  28.8    28.8
## 4      ESP  2  3.8  3.8  32.7    32.7
## 5      FRG  3  5.8  5.8  38.5    38.5
## 6      GBR  2  3.8  3.8  42.3    42.3
## 7      GER  1  1.9  1.9  44.2    44.2
## 8      NED  1  1.9  1.9  46.2    46.2
## 9      SRB  5  9.6  9.6  55.8    55.8
## 10     SWE  7 13.5 13.5  69.2    69.2
## 11     TCH  1  1.9  1.9  71.2    71.2
## 12     USA 15 28.8 28.8 100.0   100.0
library(ggplot2)
base = ggplot(data=freqCountry,aes(x=Country,y=n)) 
bar1 = base + geom_bar(stat='identity')

text1="Country in Gentlemen's Open Era"
text2="Countries"
text3="Victory Count"
text4="Traken from: Wikipedia"

bar2= bar1 + labs(title = text1,
                  x=text2,
                  y=text3,
                  caption=text4)
bar2

library(qcc)
pareto.chart(table(OpenEra$Country),cumperc = c(0,50,80,100))

##        
## Pareto chart analysis for table(OpenEra$Country)
##          Frequency  Cum.Freq. Percentage Cum.Percent.
##    USA   15.000000  15.000000  28.846154    28.846154
##     SUI   8.000000  23.000000  15.384615    44.230769
##    SWE    7.000000  30.000000  13.461538    57.692308
##    AUS    6.000000  36.000000  11.538462    69.230769
##    SRB    5.000000  41.000000   9.615385    78.846154
##    FRG    3.000000  44.000000   5.769231    84.615385
##    ESP    2.000000  46.000000   3.846154    88.461538
##    GBR    2.000000  48.000000   3.846154    92.307692
##    CRO    1.000000  49.000000   1.923077    94.230769
##    GER    1.000000  50.000000   1.923077    96.153846
##    NED    1.000000  51.000000   1.923077    98.076923
##    TCH    1.000000  52.000000   1.923077   100.000000
library(DescTools)
Mode(OpenEra$Country)
## [1] " USA"
dataTable=table(OpenEra$Country)
1/Herfindahl(dataTable)
## [1] 6.438095
dataTable=table(OpenEra$Country)
Herfindahl(dataTable)
## [1] 0.1553254

TABLA FEMENINA

  1. TABLA DE DATOS
library(htmltab)

linkPage='https://en.wikipedia.org/wiki/List_of_Wimbledon_ladies%27_singles_champions'
linkTabla='//*[@id="mw-content-text"]/div/table[4]/tbody'
OpenEraF=htmltab(doc = linkPage, which = linkTabla)

OpenEraF=OpenEraF[c(2)]
names(OpenEraF)
## [1] "Country"
str(OpenEraF)
## 'data.frame':    52 obs. of  1 variable:
##  $ Country: chr  " USA" " GBR" " AUS" " AUS" ...
head(OpenEraF)
##   Country
## 2     USA
## 3     GBR
## 4     AUS
## 5     AUS
## 6     USA
## 7     USA

2.GRÁFICOS

library(questionr)
library(magrittr) 

freqCountryF=freq(OpenEraF$Country,cum = T)%>%data.frame()
freqCountryF=data.frame(Country=row.names(freqCountryF),freqCountryF,row.names = NULL)

freqCountryF
##    Country  n   X. val. X.cum val.cum
## 1      SUI  1  1.9  1.9   1.9     1.9
## 2      AUS  3  5.8  5.8   7.7     7.7
## 3      CZE  3  5.8  5.8  13.5    13.5
## 4      ESP  2  3.8  3.8  17.3    17.3
## 5      FRA  2  3.8  3.8  21.2    21.2
## 6      FRG  2  3.8  3.8  25.0    25.0
## 7      GBR  2  3.8  3.8  28.8    28.8
## 8      GER  6 11.5 11.5  40.4    40.4
## 9      ROU  1  1.9  1.9  42.3    42.3
## 10     RUS  1  1.9  1.9  44.2    44.2
## 11     USA 29 55.8 55.8 100.0   100.0
library(ggplot2)
base1 = ggplot(data=freqCountryF,aes(x=Country,y=n)) 
bar3 = base1 + geom_bar(stat='identity')

text1="Country in Ladies' Open Era"
text2="Countries"
text3="Victory Count"
text4="Traken from: Wikipedia"

bar4= bar3 + labs(title = text1,
                  x=text2,
                  y=text3,
                  caption=text4)
bar4

library(qcc)
pareto.chart(table(OpenEraF$Country),cumperc = c(0,50,80,100))

##        
## Pareto chart analysis for table(OpenEraF$Country)
##          Frequency  Cum.Freq. Percentage Cum.Percent.
##    USA   29.000000  29.000000  55.769231    55.769231
##    GER    6.000000  35.000000  11.538462    67.307692
##    AUS    3.000000  38.000000   5.769231    73.076923
##    CZE    3.000000  41.000000   5.769231    78.846154
##    ESP    2.000000  43.000000   3.846154    82.692308
##    FRA    2.000000  45.000000   3.846154    86.538462
##    FRG    2.000000  47.000000   3.846154    90.384615
##    GBR    2.000000  49.000000   3.846154    94.230769
##     SUI   1.000000  50.000000   1.923077    96.153846
##    ROU    1.000000  51.000000   1.923077    98.076923
##    RUS    1.000000  52.000000   1.923077   100.000000
library(DescTools)
Mode(OpenEraF$Country)
## [1] " USA"
dataTable=table(OpenEraF$Country)
1/Herfindahl(dataTable)
## [1] 2.958425
dataTable=table(OpenEraF$Country)
Herfindahl(dataTable)
## [1] 0.3380178

SESIÓN 4 - ORDINALES

library(htmltab)

linkPage='https://www.nationsonline.org/oneworld/corruption.htm'
linkTabla='/html/body/table[3]/tbody'
corruption=htmltab(doc = linkPage,
                   which = linkTabla)
## Neither <thead> nor <th> information found. Taking first table row for the header. If incorrect, specifiy header argument.
## Warning: Columns [ ] seem to have no data and are removed. Use
## rm_nodata_cols = F to suppress this behavior
names(corruption)
## [1] "Rank"        "Country"     "2016  Score" "2015  Score" "2014  Score"
## [6] "2013  Score" "2012  Score" "Region"
corruption=corruption[,c(2,3,8)]
names(corruption)
## [1] "Country"     "2016  Score" "Region"
names(corruption)[2]='Score2016'
str(corruption)
## 'data.frame':    177 obs. of  3 variables:
##  $ Country  : chr  "Denmark" "New Zealand" "Finland" "Sweden" ...
##  $ Score2016: chr  "90" "90" "89" "88" ...
##  $ Region   : chr  "Europe" "Asia Pacific" "Europe" "Europe" ...
corruption$Score2016=as.numeric(corruption$Score2016) #SE DEBE CAMBIAR SCORE A NUMÉRICO
## Warning: NAs introduced by coercion
corruption[!complete.cases(corruption$Score2016),] #identificar
##                                                          Country Score2016
## 178 To get in-depth information visit:Transparency International        NA
##                                                           Region
## 178 To get in-depth information visit:Transparency International
corruption=corruption[complete.cases(corruption$Score2016),] #quedandonos con las filas con datos completos
head(corruption) #para ver las 6 primeras filas
##       Country Score2016       Region
## 2     Denmark        90       Europe
## 3 New Zealand        90 Asia Pacific
## 4     Finland        89       Europe
## 5      Sweden        88       Europe
## 6 Switzerland        86       Europe
## 7      Norway        85       Europe
# Para hacerlo, se organiza en 10 grupos
corruption$nivel=cut(corruption$Score2016,
                     breaks = 10, # cuantos grupos
                     labels = c(1:10),# nombre de los grupos
                     ordered_result = T) # resultado es ordinal

head(corruption) #ahora aparece nivel, a mayor grupo, menos corrupción
##       Country Score2016       Region nivel
## 2     Denmark        90       Europe    10
## 3 New Zealand        90 Asia Pacific    10
## 4     Finland        89       Europe    10
## 5      Sweden        88       Europe    10
## 6 Switzerland        86       Europe    10
## 7      Norway        85       Europe    10

EXPLORACIÓN DE VARIABLES ORDINALES

library(questionr)
library(magrittr) 
freqCorrup=freq(corruption$nivel,cum = T)%>%data.frame() #aqui se inserta la variable ordinal 
freqCorrup=data.frame(nivel=row.names(freqCorrup),freqCorrup,row.names = NULL) #crea un dataframe que se llama freqCrrupcion
freqCorrup
##    nivel  n   X. val. X.cum val.cum
## 1      1 13  7.4  7.4   7.4     7.4
## 2      2 19 10.8 10.8  18.2    18.2
## 3      3 37 21.0 21.0  39.2    39.2
## 4      4 36 20.5 20.5  59.7    59.7
## 5      5 17  9.7  9.7  69.3    69.3
## 6      6 14  8.0  8.0  77.3    77.3
## 7      7 17  9.7  9.7  86.9    86.9
## 8      8  6  3.4  3.4  90.3    90.3
## 9      9  9  5.1  5.1  95.5    95.5
## 10    10  8  4.5  4.5 100.0   100.0
#RENOMBRANDO CAMPOS DE LA TABLA CREADA

names(freqCorrup)[2:6] =c("absoluta","relativa","relativaVAl","relativaCum",
                          "relativaCumVAL") 

freqCorrup
##    nivel absoluta relativa relativaVAl relativaCum relativaCumVAL
## 1      1       13      7.4         7.4         7.4            7.4
## 2      2       19     10.8        10.8        18.2           18.2
## 3      3       37     21.0        21.0        39.2           39.2
## 4      4       36     20.5        20.5        59.7           59.7
## 5      5       17      9.7         9.7        69.3           69.3
## 6      6       14      8.0         8.0        77.3           77.3
## 7      7       17      9.7         9.7        86.9           86.9
## 8      8        6      3.4         3.4        90.3           90.3
## 9      9        9      5.1         5.1        95.5           95.5
## 10    10        8      4.5         4.5       100.0          100.0
library(ggplot2) #descargar la libreria
base = ggplot(data=freqCorrup,aes(x=nivel,y=absoluta))  #hacemos un grafico de barras al data frame que acabamos de crear, es decir "freqCorrup"
base1= base + scale_x_discrete(limits=freqCorrup$nivel)
bar1 = base1 + geom_bar(stat='identity') 
bar1

bar1 + labs(x="Nivel", 
            y="Cantidad",
            title="¿La mayoria de paises están libres de corrupcion?", 
            subtitle = "(por arriba de nivel 8)",
            caption = "Fuente: Transparency International")

library(qcc)
pareto.chart(table(corruption$nivel),cumperc = c(0,50,80,100))

##     
## Pareto chart analysis for table(corruption$nivel)
##       Frequency  Cum.Freq. Percentage Cum.Percent.
##   3   37.000000  37.000000  21.022727    21.022727
##   4   36.000000  73.000000  20.454545    41.477273
##   2   19.000000  92.000000  10.795455    52.272727
##   5   17.000000 109.000000   9.659091    61.931818
##   7   17.000000 126.000000   9.659091    71.590909
##   6   14.000000 140.000000   7.954545    79.545455
##   1   13.000000 153.000000   7.386364    86.931818
##   9    9.000000 162.000000   5.113636    92.045455
##   10   8.000000 170.000000   4.545455    96.590909
##   8    6.000000 176.000000   3.409091   100.000000
# no se usa la tabla de frecuencia
# se usa en tipo numerico a la ordinal

box=ggplot(corruption,aes(y=as.numeric(nivel)))+ geom_boxplot() #volvemos numerico la ordinal, para poder hacerle un boxplot
box

box + scale_y_discrete(limits = freqCorrup$nivel) #Al convertir el ordinal en numerico, aparece en la vertical numeros decimales. Podemos ver las etiquetas así:

Median(corruption$nivel)
## [1] 4
## Levels: 1 < 2 < 3 < 4 < 5 < 6 < 7 < 8 < 9 < 10

50% de los paises no pasan del nivel 4.

Dispersión Variación Modal

# mientras mayor, la moda representa menos
dataTable=table(corruption$nivel)
1-max(prop.table(dataTable))
## [1] 0.7897727

La moda NO representa al 79% de los paises.

Concentracion: Herfindahl- Hirschman

# * < 0.01 : indica que la moda no es significativa, las categorias tienen pesos similares.
# * < 0.15 : indica que la moda no es significativa, varias categorias tienen pesos similares.
# * entre 0.15 - 0.25: hay una moda.
# * > 0.25: La moda se diferencia de los demas

Herfindahl(dataTable)
## [1] 0.1339747

La moda no es significativa.

Representatividad Efectiva : Laakso - Taagepera

1/sum(prop.table(dataTable)**2)
## [1] 7.464096

Hay 7 niveles representativos.

Distancia Interquartil:

IQR(corruption$nivel)
## [1] 3

Si miras el boxplot, te das cuenta que el 50% de los valores centrales esta del nivel 3 al 6.

Desviación absoluta de la mediana:

# Mientras más se aleje de cero y sea positiva hay posible atipicos en los valores
# grandes. Mientras más se aleje de cero y sea negativa 
# hay posible atipicos en los valores pequeños.
mad(as.numeric(corruption$nivel))
## [1] 1.4826

El valor positivo indica que hay posibles valores extremos hacia los valores mayores. Así, los mejores niveles de percepcion de corrupcion (los menos corruptos) son los menos comunes en el planeta.

Sesión 5 - EXPLORACIÓN DE VALIABLES NUMÉRICAS

###PARTE 1: EXTRAYENDO LOS DATOS

link2='https://docs.google.com/spreadsheets/d/e/2PACX-1vTgDnZeJUe5Qdn-Il3Ob1u630GIYyxf5nomPu3oqrb5L31vUYCHsrtA0_tl2gEQ82mOI7-l1B9TtyZo/pub?gid=753961441&single=true&output=csv'

mineria=read.csv(link2, stringsAsFactors = F)

# que tenemos
str(mineria)
## 'data.frame':    33 obs. of  4 variables:
##  $ EMPRESA    : chr  "Ananea" "Antamina" "Ares" "Argentum" ...
##  $ Responsable: chr  "Contrata" "Empresa" "Empresa" "Contrata" ...
##  $ Tama       : chr  "Pequeña" "Grande" "Mediana" "Mediana" ...
##  $ accidentes : int  20 5 10 6 5 19 5 23 6 16 ...

###*PARTE 2 : EXPLORACIÓN GRÁFICA

NOTA: Las variables numéricas no requieren tablas de frecuencia para ser exploradas.

El grafico inicial a usar es el histograma:

library(ggplot2)
base1=ggplot(mineria,aes(x=accidentes))
histNum= base1 + geom_histogram(bins=7) 
histNum 

La exploración numérica nos debe sugerir:

Del gráfico podemos decir que, como no es simétrico, informar la media de accidentes no será muy representativa (la mediana será la mejor opción); por otro lado, como la asimetría nos muestra que los accidentes son en su mayoría pocos. Hay un numero de accidentes que se aleja hacia valores altos, pero no estamos seguros si está tan lejos del ‘centro’ para ser atípico.

Los atípicos se ven claramente en un boxplot:

base2=ggplot(mineria,aes(y=accidentes))
box=base2 + geom_boxplot() + coord_flip()

box 

El punto a la derecha confirma que hay atípicos.

Para ser más preciso en nuestra exploración, debemos calcular diversos indicadores estadísticos.

###PARTE 3: EXPLORACIÓN CON ESTADÍGRAFOS

Los estadigrafos aparecen rapidamente así:

summary(mineria$accidentes)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    5.00    5.00    8.00   10.76   13.00   42.00

Podriamos graficarlos en el boxplot:

library(ggplot2)

estadigrafos=round(as.vector(summary(mineria$accidentes)),2)

box + scale_y_continuous(breaks = estadigrafos) 

¿Te das cuenta por que hay asimetría?

Si la media es mayor que la mediana la asimetría tiende a ser positiva (cola a la derecha). Hay tendencia a la asimetría negativa (cola a la izquierda) cuando la mediana es mayor que la media. Aquí se nota claramente que hay asimetría, pero podemos confirmarla calculando el coeficiente respectivo:

library(DescTools)
Skew(mineria$accidentes,conf.level = 0.05)
##     skew   lwr.ci   upr.ci 
## 2.251112 2.570154 2.661200

La distancia intercuartilica es importante saberla:

IQR(mineria$accidentes)
## [1] 8

Es decir, entre el primer y tercer cuartil hay sólo 8 valores; asi, el 50% de los valores centrales varian en 8 valores. Así, podemos proponer que un atípico es aquel que está a una distancia lejana de estos valores centrales. Este umbral, tradicionalmente se calcula así:

# cuartil tres
q3=as.numeric(summary(mineria$accidentes)[5])

# calculando umbral (distancia del q3)
umbral= q3+1.5*IQR(mineria$accidentes)
umbral
## [1] 25

Osea, en teoria, todo valor mayor que 25 será considerado un atípico:

mineria[mineria$accidentes>umbral,]
##    EMPRESA Responsable   Tama accidentes
## 31  Volcan    Contrata Grande         42

Los accidentes pueden ser representados en el Gini:

Gini(mineria$accidentes,conf.level=0.95)
## Warning in norm.inter(t, adj.alpha): extreme order statistics used as
## endpoints
##      gini    lwr.ci    upr.ci 
## 0.3362676 0.2721479 0.4639009

Si el Gini es 0, todas las empresas causan la misma cantidad de accidentes; si fuera 1, una sola empresa causa todos los accidentes.

Normalmente al Gini le acompaña la curva de Lorenz:

library(gglorenz) # instalar 
## Registered S3 methods overwritten by 'ineq':
##   method   from     
##   plot.Lc  DescTools
##   lines.Lc DescTools
## Registered S3 methods overwritten by 'ineq':
##   method   from     
##   plot.Lc  DescTools
##   lines.Lc DescTools
base1 + gglorenz::stat_lorenz(color='red') +
    geom_abline(linetype = "dashed") + coord_fixed() +
    labs(x = "% Empresas ordenadas por accidentes causados",
         y = "% Acumulado de Accidentes",
         title = "Relación empresa / accidente",
         caption = "Fuente: MINEM")

Si la curva se acerca a la diagonal, hay igualdad de distribución: cada empresa contribuye con la misma cantidad de accidentes (Gini = 0).

SESIÓN 4 - PRÁCTICA EN CLASE

COMPLETAR XD

LINK: https://es.wikipedia.org/wiki/%C3%8Dndice_de_democracia

SESIÓN 6 - EXPLORACIÓN BIVARIADA

EXPLORACIÓN BIVARIADA

Combina todas las categorías posibles.

VARIABLE CATEGÓRICA - NUMÉRICA

  1. CARGA DE DATA
library(rio)

linkGIT="https://github.com/JoseManuelMagallanes/Estadistica_Para_AnalisisPolitico/raw/master/hsb.sav"
data=import(linkGIT)

str(data,strict.width = 'cut',witch=50)
## 'data.frame':    600 obs. of  15 variables:
##  $ ID    : num  1 2 3 4 5 6 7 8 9 10 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ SEX   : num  2 1 2 2 2 1 1 2 1 2 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ RACE  : num  2 2 2 2 2 2 2 2 2 2 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ SES   : num  1 1 1 2 2 2 1 1 2 1 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ SCTYP : num  1 1 1 1 1 1 1 1 1 1 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ HSP   : num  3 2 2 3 3 2 1 1 1 1 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ LOCUS : num  0.29 -0.42 0.71 0.06 0.22 0.46 0.44 0.68 0.06 0.05 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CONCPT: num  0.88 0.03 0.03 0.03 -0.28 0.03 -0.47 0.25 0.56 0.15 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ MOT   : num  0.67 0.33 0.67 0 0 0 0.33 1 0.33 1 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CAR   : num  10 2 9 15 1 11 10 9 9 11 ...
##   ..- attr(*, "format.spss")= chr "F5.0"
##  $ RDG   : num  33.6 46.9 41.6 38.9 36.3 49.5 62.7 44.2 46.9 44.2 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ WRTG  : num  43.7 35.9 59.3 41.1 48.9 46.3 64.5 51.5 41.1 49.5 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ MATH  : num  40.2 41.9 41.9 32.7 39.5 46.2 48 36.9 45.3 40.5 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ SCI   : num  39 36.3 44.4 41.7 41.7 41.7 63.4 49.8 47.1 39 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CIV   : num  40.6 45.6 45.6 40.6 45.6 35.6 55.6 55.6 55.6 50.6 ...
##   ..- attr(*, "format.spss")= chr "F5.2"
  1. FORMATEAR

Lea la metadata,y de formato:

data$ID=as.character(data$ID) #queremos cambiar a chr esos números

data[,c(2,3,5,6,10)]=lapply(data[,c(2,3,5,6,10)],as.factor) #queremos cambiar a texto esos números

data$SES=as.ordered(data$SES) #queremos volver ordinal la categoría socioeconómica

Ahora:

str(data,strict.width="cut",width=50)
## 'data.frame':    600 obs. of  15 variables:
##  $ ID    : chr  "1" "2" "3" "4" ...
##  $ SEX   : Factor w/ 2 levels "1","2": 2 1 2 2 2..
##  $ RACE  : Factor w/ 4 levels "1","2","3","4": 2..
##  $ SES   : Ord.factor w/ 3 levels "1"<"2"<"3": 1..
##  $ SCTYP : Factor w/ 2 levels "1","2": 1 1 1 1 1..
##  $ HSP   : Factor w/ 3 levels "1","2","3": 3 2 2..
##  $ LOCUS : num  0.29 -0.42 0.71 0.06 0.22 0.46 0..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CONCPT: num  0.88 0.03 0.03 0.03 -0.28 0.03 -..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ MOT   : num  0.67 0.33 0.67 0 0 0 0.33 1 0.33..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CAR   : Factor w/ 17 levels "1","2","3","4",...
##  $ RDG   : num  33.6 46.9 41.6 38.9 36.3 49.5 62..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ WRTG  : num  43.7 35.9 59.3 41.1 48.9 46.3 64..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ MATH  : num  40.2 41.9 41.9 32.7 39.5 46.2 48..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ SCI   : num  39 36.3 44.4 41.7 41.7 41.7 63.4..
##   ..- attr(*, "format.spss")= chr "F5.2"
##  $ CIV   : num  40.6 45.6 45.6 40.6 45.6 35.6 55..
##   ..- attr(*, "format.spss")= chr "F5.2"

Tarea: Analizar READING y SCIENCE, por sexo y nivel socioeconómico. Escribir conclusiones.

I. READING

significativa cuando la prob. es menor que 0.5.

I.1 RDG y SEX

f1=formula(RDG ~ SEX)
aggregate(f1, data,mean) 
##   SEX      RDG
## 1   1 52.36300
## 2   2 51.51682
library(knitr)
tablag= aggregate(f1, data,
          FUN = function(x) {y <- shapiro.test(x); c(y$statistic, y$p.value)})

# para que se vea mejor:
library(knitr)

shapiroTest=as.data.frame(tablag[,2])
names(shapiroTest)=c("W","Prob")

kable(cbind(tablag[1],shapiroTest))
SEX W Prob
1 0.9784886 0.0003866
2 0.9824176 0.0004953
library(ggpubr)

ggqqplot(data=data,x="RDG") + facet_grid(. ~ SEX)

Como no hay normalidad, vamos por camino NO parametrico:

PRUEBA NO PARAMÉTRICA:

wilcox sirve SOLO para variables de dos valores (ejm: hombre mujer) notch es la apertura son los dientes ( >< >< ><), si se separan la diferencia es significativo, si se juntan no.

wilcox.test(f1,data)
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  RDG by SEX
## W = 46426, p-value = 0.3962
## alternative hypothesis: true location shift is not equal to 0
ggplot(data=data, aes(x=SEX, y=RDG)) + geom_boxplot(notch = T)

Concluyendo que NO hay diferencia de medias.

I.2 RDG y SES

PRUEBA PARAMÉTRICA:

kruskal.test cuando hay DOS O MÁS VARIABLES

f2=formula(RDG ~ SES)
aggregate(f2, data,mean) 
##   SES      RDG
## 1   1 47.33597
## 2   2 51.92542
## 3   3 55.77593
library(knitr)
tablag=aggregate(f2, data,
          FUN = function(x) {y <- shapiro.test(x); c(y$statistic, y$p.value)})

# para que se vea mejor:

shapiroTest=as.data.frame(tablag[,2])
names(shapiroTest)=c("W","Prob")

kable(cbind(tablag[1],shapiroTest))
SES W Prob
1 0.9533579 0.0001203
2 0.9841816 0.0022243
3 0.9814021 0.0282263

Aqui lo puedes graficar:

library(ggpubr)
ggqqplot(data=data,x="RDG") + facet_grid(. ~ SES)

Opcion No Paramétrica para politomica:

kruskal.test(f2,data)
## 
##  Kruskal-Wallis rank sum test
## 
## data:  RDG by SES
## Kruskal-Wallis chi-squared = 52.583, df = 2, p-value = 3.818e-12

e-12 = 10 a la menos doce

Mismo resultado.

Visualmente:

ggplot(data=data, aes(x=SES, y=RDG)) + geom_boxplot(notch = T)

El valor medio que se alejaria seria el SES=1 de todos los demas.

I. SCIENCE

I.1 SCI y SEX

f1=formula(SCI ~ SEX)
aggregate(f1, data,mean) 
##   SEX      SCI
## 1   1 53.23004
## 2   2 50.53884
library(knitr)
tablag=aggregate(f1, data,
          FUN = function(x) {y <- shapiro.test(x); c(y$statistic, y$p.value)})

# para que se vea mejor:

shapiroTest=as.data.frame(tablag[,2])
names(shapiroTest)=c("W","Prob")

kable(cbind(tablag[1],shapiroTest))
SEX W Prob
1 0.9787394 0.0004268
2 0.9798800 0.0001525

Aqui lo puedes graficar:

library(ggpubr)
ggqqplot(data=data,x="SCI") + facet_grid(. ~ SEX)

Como no hay normalidad, vamos por camino NO parametrico:

wilcox.test(f1,data)
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  SCI by SEX
## W = 51631, p-value = 0.0009173
## alternative hypothesis: true location shift is not equal to 0

Visualmente:

ggplot(data=data, aes(x=SEX, y=SCI)) + geom_boxplot(notch = T)

Concluyendo que SI hay diferencia de medias.

I.2 SCI y SES

f2=formula(SCI ~ SES)
aggregate(f2, data,mean) 
##   SES      SCI
## 1   1 47.30576
## 2   2 51.93010
## 3   3 55.28025
library(knitr)
tablag=aggregate(f2, data,
          FUN = function(x) {y <- shapiro.test(x); c(y$statistic, y$p.value)})

# para que se vea mejor:

shapiroTest=as.data.frame(tablag[,2])
names(shapiroTest)=c("W","Prob")

kable(cbind(tablag[1],shapiroTest))
SES W Prob
1 0.9773277 0.0205115
2 0.9833695 0.0015284
3 0.9574177 0.0000744

Aqui lo puedes graficar:

library(ggpubr)
ggqqplot(data=data,x="SCI") + facet_grid(. ~ SES)

Ningun grupo es normal. Vamos por no parametrico:

kruskal.test(f2,data)
## 
##  Kruskal-Wallis rank sum test
## 
## data:  SCI by SES
## Kruskal-Wallis chi-squared = 52.806, df = 2, p-value = 3.415e-12

Hay diferencias!

Visualmente:

ggplot(data=data, aes(x=SES, y=SCI)) + geom_boxplot(notch = T)

Los tres grupos se diferencian.

EXPLORACION BIVARIADA DESDE TABLAS WEB

1. Carga de data:

Para esta sesión usaremos estos datos:

Traigamosla desde Google:

link="https://docs.google.com/spreadsheets/d/e/2PACX-1vQ_VNceU6ncsQs-_KFvkQsv2XqYKRCMyRYCDYQFosH5bo6Yt-l1gE8ZRdP44m4Rh8lQB2nOY-Y-p0ZP/pub?gid=0&single=true&output=csv"

hsb=read.csv(link, stringsAsFactors = F)

2. EXPLOREMOS

¿Qué tenemos?

Esto es lo R ha traido:

str(hsb)
## 'data.frame':    600 obs. of  15 variables:
##  $ ID    : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ SEX   : int  2 1 2 2 2 1 1 2 1 2 ...
##  $ RACE  : int  2 2 2 2 2 2 2 2 2 2 ...
##  $ SES   : int  1 1 1 2 2 2 1 1 2 1 ...
##  $ SCTYP : int  1 1 1 1 1 1 1 1 1 1 ...
##  $ HSP   : int  3 2 2 3 3 2 1 1 1 1 ...
##  $ LOCUS : num  0.29 -0.42 0.71 0.06 0.22 0.46 0.44 0.68 0.06 0.05 ...
##  $ CONCPT: num  0.88 0.03 0.03 0.03 -0.28 0.03 -0.47 0.25 0.56 0.15 ...
##  $ MOT   : num  0.67 0.33 0.67 0 0 0 0.33 1 0.33 1 ...
##  $ CAR   : int  10 2 9 15 1 11 10 9 9 11 ...
##  $ RDG   : num  33.6 46.9 41.6 38.9 36.3 49.5 62.7 44.2 46.9 44.2 ...
##  $ WRTG  : num  43.7 35.9 59.3 41.1 48.9 46.3 64.5 51.5 41.1 49.5 ...
##  $ MATH  : num  40.2 41.9 41.9 32.7 39.5 46.2 48 36.9 45.3 40.5 ...
##  $ SCI   : num  39 36.3 44.4 41.7 41.7 41.7 63.4 49.8 47.1 39 ...
##  $ CIV   : num  40.6 45.6 45.6 40.6 45.6 35.6 55.6 55.6 55.6 50.6 ...

3. PRE PROCESAMIENTO:

No se puede empezar el análisis sin adecuar la data a la metadata

La data tiene que reformatearse segun lo que indica la metadata:

Los cambios que se necesitan son:

# id como texto (pues no es variable, sino "identificador")
hsb$ID=as.character(hsb$ID)

# estas variables como CATEGORICAS NOMINALES
hsb[,c(2,3,5,6,10)]=lapply(hsb[,c(2,3,5,6,10)],as.factor)

# estas variables como CATEGORICAS ORDINALES
hsb$HSP=as.ordered(hsb$HSP)

Note que el formateo NO INCLUYO RECODIFICACIÓN. La recodificación es necesaria cuando la variable categórica presenta etiquetas como categorías (vera ese caso cuando trabaje el Indice de Democracia, para las variables tipo de regimen y continente).

Note además que NO todas las columnas serán variables, otras sera identificadores o claves o keys. Los identificadores deben permanecer como texto (char).

Ahora veamos nueva estructura:

str(hsb,strict.width="cut",width=50)
## 'data.frame':    600 obs. of  15 variables:
##  $ ID    : chr  "1" "2" "3" "4" ...
##  $ SEX   : Factor w/ 2 levels "1","2": 2 1 2 2 2..
##  $ RACE  : Factor w/ 4 levels "1","2","3","4": 2..
##  $ SES   : int  1 1 1 2 2 2 1 1 2 1 ...
##  $ SCTYP : Factor w/ 2 levels "1","2": 1 1 1 1 1..
##  $ HSP   : Ord.factor w/ 3 levels "1"<"2"<"3": 3..
##  $ LOCUS : num  0.29 -0.42 0.71 0.06 0.22 0.46 0..
##  $ CONCPT: num  0.88 0.03 0.03 0.03 -0.28 0.03 -..
##  $ MOT   : num  0.67 0.33 0.67 0 0 0 0.33 1 0.33..
##  $ CAR   : Factor w/ 17 levels "1","2","3","4",...
##  $ RDG   : num  33.6 46.9 41.6 38.9 36.3 49.5 62..
##  $ WRTG  : num  43.7 35.9 59.3 41.1 48.9 46.3 64..
##  $ MATH  : num  40.2 41.9 41.9 32.7 39.5 46.2 48..
##  $ SCI   : num  39 36.3 44.4 41.7 41.7 41.7 63.4..
##  $ CIV   : num  40.6 45.6 45.6 40.6 45.6 35.6 55..

4. Probando HIPOTESIS a nivel bivariado

Lo clave para probar hipotesis es saber la hipótesis nula de la prueba estadística que le toque hacer.

la prueba estadística depende de saber si la variable numérica a analizar se distribuye normalmente:

Por ejemplo, para todos nuestros ejemplos, usaremos a MATH como nuestra variable numérica de interés. Veamos la distribuición de esta variable:

library(ggplot2)

base=ggplot(data=hsb, aes(x=MATH))
base + geom_histogram(bins = 20)

Usaremos tests y graficas para comprobar si MATH se distribuye (u otra variabe numerica) tiene una distribución sufientemente cercana a la normal. El test de normalidad a utilizar será el de Shapiro Wilk, cuya hipotesis nula es que la variable se distribuye normalmente. Recuerda que si hay normalidad se usarán técnicas paramétricas, si no la hay, las NO paramétricas.

IMPORTANTE: Todas las hipotesis nulas serán rechazadas si el test aplicado nos devuelve un p-valor (p-value / prob) menor a 0.05. Cuando un test de hipotesis tiene ese valor, se dice que significativo.

a. Tipo 1: NUM-DICO

Aqui plantearemos hipótesis entre una variable numerica y una variable categorica dicotómica (solo dos niveles).

  • HIPOTESIS NULA o H0: Los promedios de las variable numerica en cada grupo de la dicotómica no se diferencian.

Si tenemos que estos son los promedios de matematicas para hombres y mujeres:

f1=formula(MATH ~ SEX)
aggregate(f1, hsb,mean) 
##   SEX     MATH
## 1   1 52.34542
## 2   2 51.43456

Podemos inferir que a los hombres les va mejor en MATH?

  1. Paso 1: Decidiendo si es no no paramétrico

Usemos el método gráfico:

library(ggpubr)

ggqqplot(data=hsb,x="MATH") + facet_grid(. ~ SEX)

Si los puntos se alejan mucho de la diagonal, se aleja de la normalidad.

Como es dificil hacerlo visualmente siempre, podemos usar el test de Shapiro-Wilk, que nos reporta la probabilidad que los datos tengan esa distribución.

# funcion ad-hoc
normalidadTest=function(x) {y =shapiro.test(x); 
                            c(y$statistic, y$p.value)}
# calculando
resultado= aggregate(f1, hsb,
                     FUN = normalidadTest) 


# mostrando resultado
library(knitr)

shapiroTest=as.data.frame(resultado[,2])
names(shapiroTest)=c("SW_Statistic","Probabilidad")
kable(cbind(resultado[1],shapiroTest))
SEX SW_Statistic Probabilidad
1 0.9837903 0.0034565
2 0.9790040 0.0001031

El test nos dice que la probabilidad que la variable MATH se comporte como la curva normal es muy baja (considera bajo si es menor a 0.05). Se rechaza la hipótesis que MATH tiene distribución normal en cada nivel de SEXO.

2. Aplicando TEST para aceptar o rechazar la H0:

Ya sabemos que lo que corresponde utilizar, si ya sabemos que no es NORMAL, es alguna prueba no paramétrica que me informe si los promedios difieren segun grupo. Pero veamos ambos tipos de pruebas:

  • Opcion Paramétrica para dicotómica:

Si hay normalidad usa la prueba t:

t.test(f1,hsb)
## 
##  Welch Two Sample t-test
## 
## data:  MATH by SEX
## t = 1.1722, df = 560.59, p-value = 0.2416
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -0.6154067  2.4371360
## sample estimates:
## mean in group 1 mean in group 2 
##        52.34542        51.43456

Esta prueba informa la probabilidad que la media de MATH sea la misma en ambos grupos de SEX. Como ves, el p-value es mayor a 0.05, por lo que aceptamos la H0 de la prueba t.

  • Opcion No Paramétrica para dicotómica:

Si no hay normalidad usa la prueba Mann-Whitney:

# el test de wilcoxon devuelve Mann-Whitney 
# al recibir "f1"
wilcox.test(f1,hsb)
## 
##  Wilcoxon rank sum test with continuity correction
## 
## data:  MATH by SEX
## W = 46789, p-value = 0.3086
## alternative hypothesis: true location shift is not equal to 0

Igualmente, el p-value sale NO signficativo. SE acepta la H0 del Mann-Whitney.

b. Tipo 2: NUM-POLI

Aqui plantearemos hipótesis entre una variable numerica y una variable categorica politómica (más de dos niveles).

  • HIPOTESIS NULA o H0: Los promedios de las variable numerica en cada grupo de la politómica no se diferencian. Si tenemos que estos son los promedios de matematicas según programa escolar:
f2=formula(MATH ~ HSP)
aggregate(f2, hsb,mean) 
##   HSP     MATH
## 1   1 55.81071
## 2   2 49.09172
## 3   3 46.26803

Podemos inferir que a los alumnos del programa general les va mejor en MATH?

1. Paso 1: Decidiendo si es no no paramétrico

Usemos el método gráfico:

library(ggpubr)
ggqqplot(data=hsb,x="MATH") + facet_grid(. ~ HSP)

Ahora hagamos el test de Shapiro Wilk

# calculando
resultado= aggregate(f2, hsb,
                     FUN = normalidadTest) 


# mostrando resultado
library(knitr)

shapiroTest=as.data.frame(resultado[,2])
names(shapiroTest)=c("SW_Statistic","Probabilidad")
kable(cbind(resultado[1],shapiroTest))
HSP SW_Statistic Probabilidad
1 0.9888836 0.0187048
2 0.9810514 0.0423975
3 0.9512192 0.0000496

Como al menos una tiene probabilidad menor a 0.05, debemos ir por el camino no paramétrico.

2. Aplicando TEST para aceptar o rechazar la H0:

  • Opcion Paramétrica para politomica:

Aquí corresponde la pruea F de Schnedecor, conocida tambien como one-way ANOVA:

summary(aov(f2, data=hsb))
##              Df Sum Sq Mean Sq F value Pr(>F)    
## HSP           2  10515    5258   73.72 <2e-16 ***
## Residuals   597  42579      71                   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Los astericos indican si el H0 es significativo. Podemos rechazarlo, de ahi que al menos un promedio difiere de los demás. Tratemos de detectar las diferencias:

library(ggpubr)
ggerrorplot(hsb, x = "HSP", 
            y = "MATH", 
            desc_stat = "mean_ci"
            )

El nivel 1 se diferenciaría de los demás.

  • Opcion No Paramétrica para politomica:

Aquí puedes usar la prueba de Kruskal-Wallis:

kruskal.test(f2,hsb)
## 
##  Kruskal-Wallis rank sum test
## 
## data:  MATH by HSP
## Kruskal-Wallis chi-squared = 121.26, df = 2, p-value < 2.2e-16

Aqui no muestra asteriscos, pero la probabilidad (p-value) es también menor a 0.05.

Visualmente:

ggplot(data=hsb, aes(x=HSP, y=MATH)) + geom_boxplot(notch = T)

En este caso, se ha puesto un ‘notch’ al boxplot. Si los notches se intersectan, se asume igualdad de medianas, de ahí que la opcion 1 es diferente a las demás.