R Markdown

1.Introducción

Objetivo

En esta sección se cargan las librerías que se utilizarán durante el análisis exploratorio de datos. Estas librerías permiten trabajar con bases de datos, realizar transformaciones, calcular medidas estadísticas y elaborar gráficos

Código

library(lsm)      # Para descargar una base de datos
library(dplyr)
## 
## Adjuntando el paquete: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(moments)  # Para hallar las medidas de forma
library(e1071)
## 
## Adjuntando el paquete: 'e1071'
## The following objects are masked from 'package:moments':
## 
##     kurtosis, moment, skewness
library(ggplot2)
## 
## Adjuntando el paquete: 'ggplot2'
## The following object is masked from 'package:e1071':
## 
##     element

2 Data frame

Objetivo

En esta sección se explica qué es un data frame y por qué es importante para realizar análisis estadísticos en R. Un data frame permite organizar los datos en forma de tabla, donde las filas representan las observaciones y las columnas representan las variables.

3 Nuestro data frame

Objetivo

En esta sección se carga el conjunto de datos survey, perteneciente al paquete lsm. Esta base contiene información obtenida mediante una encuesta realizada a estudiantes universitarios. El conjunto de datos contiene 800 observaciones y 66 variables.

datosCompleto <- lsm::survey

4 Revisando el data frame

Objetivo

En esta sección se revisa la información contenida en el data frame. Para esto utilizamos la función head(), que permite visualizar las primeras observaciones de la base de datos

4.0.1 Visualizar una parte de la información con head()

Código

head(datosCompleto)        #A) Por defecto, solo las primeras 6 observaciones 
## # A tibble: 6 × 66
##   Observation ID       Gender Like    Age Smoke Height Weight   BMI School SES  
##         <dbl> <chr>    <chr>  <chr> <dbl> <chr>  <dbl>  <dbl> <dbl> <chr>  <chr>
## 1           1 SB11201… Female TV     21.4 No      1.58     75  30.0 Priva… Medi…
## 2           2 SB11201… Male   Netw…  21.1 Yes     1.6      80  31.2 Public High 
## 3           3 SB11201… Male   Netw…  20.9 Yes     1.5      64  28.4 Priva… High 
## 4           4 SB11201… Male   TV     18.4 Yes     1.53     49  20.9 Public Low  
## 5           5 SB11201… Female TV     16.6 Yes     1.78     82  25.9 Priva… High 
## 6           6 SB11201… Female Netw…  16.0 No      1.65     80  29.4 Public Low  
## # ℹ 55 more variables: Enrollment <chr>, Score <dbl>, MotherHeight <chr>,
## #   MotherAge <dbl>, MotherCHD <dbl>, FatherHeight <chr>, FatherAge <dbl>,
## #   FatherCHD <dbl>, Status <chr>, SemAcum <dbl>, Exam1 <dbl>, Exam2 <dbl>,
## #   Exam3 <dbl>, Exam4 <dbl>, ExamAcum <dbl>, Definitive <dbl>, Expense <dbl>,
## #   Income <dbl>, Gas <dbl>, Course <chr>, Law <chr>, Economic <chr>,
## #   Race <chr>, Region <chr>, EMO1 <dbl>, EMO2 <dbl>, EMO3 <dbl>, EMO4 <dbl>,
## #   EMO5 <dbl>, GOAL1 <chr>, GOAL2 <chr>, GOAL3 <chr>, Pre_STAT1 <dbl>, …
head(datosCompleto, 3)     #B) Solo las primeras 3 observaciones
## # A tibble: 3 × 66
##   Observation ID       Gender Like    Age Smoke Height Weight   BMI School SES  
##         <dbl> <chr>    <chr>  <chr> <dbl> <chr>  <dbl>  <dbl> <dbl> <chr>  <chr>
## 1           1 SB11201… Female TV     21.4 No      1.58     75  30.0 Priva… Medi…
## 2           2 SB11201… Male   Netw…  21.1 Yes     1.6      80  31.2 Public High 
## 3           3 SB11201… Male   Netw…  20.9 Yes     1.5      64  28.4 Priva… High 
## # ℹ 55 more variables: Enrollment <chr>, Score <dbl>, MotherHeight <chr>,
## #   MotherAge <dbl>, MotherCHD <dbl>, FatherHeight <chr>, FatherAge <dbl>,
## #   FatherCHD <dbl>, Status <chr>, SemAcum <dbl>, Exam1 <dbl>, Exam2 <dbl>,
## #   Exam3 <dbl>, Exam4 <dbl>, ExamAcum <dbl>, Definitive <dbl>, Expense <dbl>,
## #   Income <dbl>, Gas <dbl>, Course <chr>, Law <chr>, Economic <chr>,
## #   Race <chr>, Region <chr>, EMO1 <dbl>, EMO2 <dbl>, EMO3 <dbl>, EMO4 <dbl>,
## #   EMO5 <dbl>, GOAL1 <chr>, GOAL2 <chr>, GOAL3 <chr>, Pre_STAT1 <dbl>, …

4.0.2 Visualizar una parte de la información con tail()

Objetivo

En este apartado se utiliza la función tail() para visualizar las últimas observaciones del data frame. Por defecto, muestra las últimas 6 filas, pero también podemos indicar una cantidad específica de observaciones.

Código

tail(datosCompleto)        #C) Por defecto, solo las últimas 6 observaciones 
## # A tibble: 6 × 66
##   Observation ID       Gender Like    Age Smoke Height Weight   BMI School SES  
##         <dbl> <chr>    <chr>  <chr> <dbl> <chr>  <dbl>  <dbl> <dbl> <chr>  <chr>
## 1         795 AC31201… Female <NA>   NA   <NA>    1.64     NA  NA   <NA>   Low  
## 2         796 AC31201… Female TV     13.5 <NA>    1.71     78  26.7 Public <NA> 
## 3         797 AC31201… <NA>   Netw…  15.8 No      1.68     53  18.8 Priva… Medi…
## 4         798 AC31201… Male   <NA>   15.7 No     NA        83  NA   <NA>   Low  
## 5         799 AC31201… Female TV     NA   No      1.76     73  23.6 Priva… Low  
## 6         800 AC31201… Male   TV     16.6 No      1.62     70  26.7 Priva… <NA> 
## # ℹ 55 more variables: Enrollment <chr>, Score <dbl>, MotherHeight <chr>,
## #   MotherAge <dbl>, MotherCHD <dbl>, FatherHeight <chr>, FatherAge <dbl>,
## #   FatherCHD <dbl>, Status <chr>, SemAcum <dbl>, Exam1 <dbl>, Exam2 <dbl>,
## #   Exam3 <dbl>, Exam4 <dbl>, ExamAcum <dbl>, Definitive <dbl>, Expense <dbl>,
## #   Income <dbl>, Gas <dbl>, Course <chr>, Law <chr>, Economic <chr>,
## #   Race <chr>, Region <chr>, EMO1 <dbl>, EMO2 <dbl>, EMO3 <dbl>, EMO4 <dbl>,
## #   EMO5 <dbl>, GOAL1 <chr>, GOAL2 <chr>, GOAL3 <chr>, Pre_STAT1 <dbl>, …
tail(datosCompleto, 2)     #D) Solo las últimas 2 observaciones
## # A tibble: 2 × 66
##   Observation ID       Gender Like    Age Smoke Height Weight   BMI School SES  
##         <dbl> <chr>    <chr>  <chr> <dbl> <chr>  <dbl>  <dbl> <dbl> <chr>  <chr>
## 1         799 AC31201… Female TV     NA   No      1.76     73  23.6 Priva… Low  
## 2         800 AC31201… Male   TV     16.6 No      1.62     70  26.7 Priva… <NA> 
## # ℹ 55 more variables: Enrollment <chr>, Score <dbl>, MotherHeight <chr>,
## #   MotherAge <dbl>, MotherCHD <dbl>, FatherHeight <chr>, FatherAge <dbl>,
## #   FatherCHD <dbl>, Status <chr>, SemAcum <dbl>, Exam1 <dbl>, Exam2 <dbl>,
## #   Exam3 <dbl>, Exam4 <dbl>, ExamAcum <dbl>, Definitive <dbl>, Expense <dbl>,
## #   Income <dbl>, Gas <dbl>, Course <chr>, Law <chr>, Economic <chr>,
## #   Race <chr>, Region <chr>, EMO1 <dbl>, EMO2 <dbl>, EMO3 <dbl>, EMO4 <dbl>,
## #   EMO5 <dbl>, GOAL1 <chr>, GOAL2 <chr>, GOAL3 <chr>, Pre_STAT1 <dbl>, …

4.0.3 Analizar la estructura del data frame

Objetivo

En este apartado se utiliza la función str() para conocer la estructura del data frame datosCompleto. Esta función permite identificar el número de observaciones y variables, además del tipo de cada variable y algunos de los primeros valores registrados.

Código

str(datosCompleto)   #A) Estructura de los datos
## tibble [800 × 66] (S3: tbl_df/tbl/data.frame)
##  $ Observation : num [1:800] 1 2 3 4 5 6 7 8 9 10 ...
##  $ ID          : chr [1:800] "SB11201910010435" "SB11201910004475" "SB11201910011427" "SB11201910041975" ...
##  $ Gender      : chr [1:800] "Female" "Male" "Male" "Male" ...
##  $ Like        : chr [1:800] "TV" "Network" "Network" "TV" ...
##  $ Age         : num [1:800] 21.4 21.1 20.9 18.4 16.6 ...
##  $ Smoke       : chr [1:800] "No" "Yes" "Yes" "Yes" ...
##  $ Height      : num [1:800] 1.58 1.6 1.5 1.53 1.78 1.65 1.73 1.53 1.64 1.52 ...
##  $ Weight      : num [1:800] 75 80 64 49 82 80 90 55 50 78 ...
##  $ BMI         : num [1:800] 30 31.2 28.4 20.9 25.9 ...
##  $ School      : chr [1:800] "Private" "Public" "Private" "Public" ...
##  $ SES         : chr [1:800] "Medium" "High" "High" "Low" ...
##  $ Enrollment  : chr [1:800] "Credit" "Scholarship" "Scholarship" "Credit" ...
##  $ Score       : num [1:800] 81 78 77 70 68 65 54 50 36 35 ...
##  $ MotherHeight: chr [1:800] "Short_M" "Normal_M" "Normal_M" "Tall_M" ...
##  $ MotherAge   : num [1:800] 41 45 45 45 46 46 47 48 48 48 ...
##  $ MotherCHD   : num [1:800] 0 0 0 0 1 0 0 0 0 1 ...
##  $ FatherHeight: chr [1:800] "Normal_F" "Short_F" "Tall_F" "Short_F" ...
##  $ FatherAge   : num [1:800] 40 43 44 45 45 46 46 48 48 49 ...
##  $ FatherCHD   : num [1:800] 1 1 1 2 1 1 1 1 1 1 ...
##  $ Status      : chr [1:800] "Distinguished" "Distinguished" "Distinguished" "Regular" ...
##  $ SemAcum     : num [1:800] 4.25 2.8 4.15 3.2 3.45 2.75 2.7 4.35 4.3 2.8 ...
##  $ Exam1       : num [1:800] 1.5 2.3 3.4 2.5 3.1 3.8 5 4 2.5 2.4 ...
##  $ Exam2       : num [1:800] 5 4.9 3.6 4.2 3.5 4.4 3 2.3 3.3 2.6 ...
##  $ Exam3       : num [1:800] 5 3.7 2 5 5 4.2 3.5 4.6 3.8 4.3 ...
##  $ Exam4       : num [1:800] 4.5 3.3 1.9 2.5 3 5 3.6 4.3 1.9 5 ...
##  $ ExamAcum    : num [1:800] 16 14.2 10.9 14.2 14.6 17.4 15.1 15.2 11.5 14.3 ...
##  $ Definitive  : num [1:800] 4 3.55 2.73 3.55 3.65 ...
##  $ Expense     : num [1:800] 48.9 72.1 85.2 56.6 64.6 63 40.8 65.4 37.3 63 ...
##  $ Income      : num [1:800] 1.61 2.07 2.84 1.55 2.32 2.1 1.69 2.18 1.71 2.1 ...
##  $ Gas         : num [1:800] 27.4 24.2 22.3 23.1 27.3 ...
##  $ Course      : chr [1:800] "Face-to-Face" "Virtual" "Face-to-Face" "Virtual" ...
##  $ Law         : chr [1:800] "Agree" "Agree" "Agree" "Agree" ...
##  $ Economic    : chr [1:800] "Regular" "Good" "Regular" "Bad" ...
##  $ Race        : chr [1:800] "Ethnic" "Ethnic" "Ethnic" "Ethnic" ...
##  $ Region      : chr [1:800] "North" "Center" "North" "Center" ...
##  $ EMO1        : num [1:800] 1 4 3 4 2 3 2 3 4 2 ...
##  $ EMO2        : num [1:800] 2 4 1 2 1 1 4 1 2 2 ...
##  $ EMO3        : num [1:800] 2 1 3 3 2 4 2 4 3 3 ...
##  $ EMO4        : num [1:800] 1 2 3 1 4 2 3 2 1 1 ...
##  $ EMO5        : num [1:800] 4 1 2 2 2 2 1 1 2 2 ...
##  $ GOAL1       : chr [1:800] "Strongly agree" "Undecided" "Agree" "Agree" ...
##  $ GOAL2       : chr [1:800] "Agree" "Disagree" "Disagree" "Undecided" ...
##  $ GOAL3       : chr [1:800] "Strongly agree" "Disagree" "Agree" "Strongly agree" ...
##  $ Pre_STAT1   : num [1:800] 2 1 5 4 1 4 4 2 2 2 ...
##  $ Pre_STAT2   : num [1:800] 4 1 1 3 4 1 2 3 3 5 ...
##  $ Pre_STAT3   : num [1:800] 2 1 3 1 1 5 4 3 3 2 ...
##  $ Pre_STAT4   : num [1:800] 5 1 1 2 2 3 2 3 2 4 ...
##  $ Post_STAT1  : num [1:800] 4 5 5 3 5 2 3 3 2 5 ...
##  $ Post_STAT2  : num [1:800] 5 1 2 2 3 3 2 3 2 3 ...
##  $ Post_STAT3  : num [1:800] 2 3 3 4 3 5 5 4 5 4 ...
##  $ Post_STAT4  : num [1:800] 2 3 3 5 4 4 3 5 5 1 ...
##  $ Pre_IDARE1  : chr [1:800] "Quite a bit" "Quite a bit" "Quite a bit" "Little" ...
##  $ Pre_IDARE2  : chr [1:800] "Little" "Little" "Little" "Nothing" ...
##  $ Pre_IDARE3  : chr [1:800] "Quite a bit" "A lot" "Quite a bit" "Quite a bit" ...
##  $ Pre_IDARE4  : chr [1:800] "Quite a bit" "Nothing" "Quite a bit" "Quite a bit" ...
##  $ Pre_IDARE5  : chr [1:800] "Little" "Quite a bit" "Little" "Nothing" ...
##  $ Post_IDARE1 : chr [1:800] "A lot" "A little" "Nothing" "Quite a bit" ...
##  $ Post_IDARE2 : chr [1:800] "A lot" "Nothing" "Quite a bit" "A little" ...
##  $ Post_IDARE3 : chr [1:800] "A little" "Quite a bit" "Nothing" "A lot" ...
##  $ Post_IDARE4 : chr [1:800] "Quite a bit" "A lot" "Nothing" "Quite a bit" ...
##  $ Post_IDARE5 : chr [1:800] "A lot" "Quite a bit" "Nothing" "A lot" ...
##  $ PSICO1      : chr [1:800] "Frequently" "Frequently" "Sometimes" "Almost always" ...
##  $ PSICO2      : chr [1:800] "Almost always" "Sometimes" "Sometimes" "Frequently" ...
##  $ PSICO3      : chr [1:800] "Frequently" "Sometimes" "Sometimes" "Frequently" ...
##  $ PSICO4      : chr [1:800] "Almost always" "Frequently" "Frequently" "Almost never" ...
##  $ PSICO5      : chr [1:800] "Almost always" "Frequently" "Sometimes" "Sometimes" ...

4.0.4 Explorar los nombres de las variables

Objetivo

En este apartado se utiliza la función names() para identificar los nombres de las variables o columnas que contiene el data frame datosCompleto.

Código

names(datosCompleto)    #A) Muestra los nombres de las columnas (variables).
##  [1] "Observation"  "ID"           "Gender"       "Like"         "Age"         
##  [6] "Smoke"        "Height"       "Weight"       "BMI"          "School"      
## [11] "SES"          "Enrollment"   "Score"        "MotherHeight" "MotherAge"   
## [16] "MotherCHD"    "FatherHeight" "FatherAge"    "FatherCHD"    "Status"      
## [21] "SemAcum"      "Exam1"        "Exam2"        "Exam3"        "Exam4"       
## [26] "ExamAcum"     "Definitive"   "Expense"      "Income"       "Gas"         
## [31] "Course"       "Law"          "Economic"     "Race"         "Region"      
## [36] "EMO1"         "EMO2"         "EMO3"         "EMO4"         "EMO5"        
## [41] "GOAL1"        "GOAL2"        "GOAL3"        "Pre_STAT1"    "Pre_STAT2"   
## [46] "Pre_STAT3"    "Pre_STAT4"    "Post_STAT1"   "Post_STAT2"   "Post_STAT3"  
## [51] "Post_STAT4"   "Pre_IDARE1"   "Pre_IDARE2"   "Pre_IDARE3"   "Pre_IDARE4"  
## [56] "Pre_IDARE5"   "Post_IDARE1"  "Post_IDARE2"  "Post_IDARE3"  "Post_IDARE4" 
## [61] "Post_IDARE5"  "PSICO1"       "PSICO2"       "PSICO3"       "PSICO4"      
## [66] "PSICO5"

4.0.5 Explorar tamaños

Objetivo

En este apartado se utilizan diferentes funciones para conocer el tamaño y las dimensiones del objeto datosCompleto. Esto permite identificar el número de variables y observaciones que contiene la base de datos.

Código

length(datosCompleto)   #A) Revisando número de variables del objeto
## [1] 66
dim(datosCompleto)      #B Muestra las dimensiones del objeto.
## [1] 800  66
ncol(datosCompleto)     #C) Muestra el número de columnas del objeto.
## [1] 66
nrow(datosCompleto)     #D) Muestra el número de filas del objeto.
## [1] 800

5.0.2 Ejemplos con la función corchete [ ]

Ejemplo 1

Objetivo

Seleccionar las observaciones de la 1 a la 10 y únicamente las variables de la 2 a la 7 de datosCompleto, creando un nuevo data frame llamado Muestra1.

Código

Muestra1 <- datosCompleto[1:10,2:7]       # A) Un nuevo data frame 
Muestra1
## # A tibble: 10 × 6
##    ID               Gender Like      Age Smoke Height
##    <chr>            <chr>  <chr>   <dbl> <chr>  <dbl>
##  1 SB11201910010435 Female TV       21.4 No      1.58
##  2 SB11201910004475 Male   Network  21.1 Yes     1.6 
##  3 SB11201910011427 Male   Network  20.9 Yes     1.5 
##  4 SB11201910041975 Male   TV       18.4 Yes     1.53
##  5 SB11201910013623 Female TV       16.6 Yes     1.78
##  6 SB11201910038122 Female Network  16.0 No      1.65
##  7 SB11201910037905 Female TV       19.3 Yes     1.73
##  8 SB11201910038140 Female TV       18.6 Yes     1.53
##  9 SB11201910038005 Female TV       17.0 Yes     1.64
## 10 SB11201910037919 Male   TV       19.7 Yes     1.52

Ejemplo 2

Muestra1[3,2]           # A) Solo la fila 3 y la columna 2
## # A tibble: 1 × 1
##   Gender
##   <chr> 
## 1 Male
Muestra1[,2]            # B) Todas las filas (por el espacio en blanco) y solo la columna 2
## # A tibble: 10 × 1
##    Gender
##    <chr> 
##  1 Female
##  2 Male  
##  3 Male  
##  4 Male  
##  5 Female
##  6 Female
##  7 Female
##  8 Female
##  9 Female
## 10 Male
Muestra1[3,]            # C) Solo la fila 3 y todas las columnas (por el espacio en blanco)
## # A tibble: 1 × 6
##   ID               Gender Like      Age Smoke Height
##   <chr>            <chr>  <chr>   <dbl> <chr>  <dbl>
## 1 SB11201910011427 Male   Network  20.9 Yes      1.5
Muestra1[-5, ]          # D) Quitar la fila 5 (por eso el signo menos) y dejar todas las columnas
## # A tibble: 9 × 6
##   ID               Gender Like      Age Smoke Height
##   <chr>            <chr>  <chr>   <dbl> <chr>  <dbl>
## 1 SB11201910010435 Female TV       21.4 No      1.58
## 2 SB11201910004475 Male   Network  21.1 Yes     1.6 
## 3 SB11201910011427 Male   Network  20.9 Yes     1.5 
## 4 SB11201910041975 Male   TV       18.4 Yes     1.53
## 5 SB11201910038122 Female Network  16.0 No      1.65
## 6 SB11201910037905 Female TV       19.3 Yes     1.73
## 7 SB11201910038140 Female TV       18.6 Yes     1.53
## 8 SB11201910038005 Female TV       17.0 Yes     1.64
## 9 SB11201910037919 Male   TV       19.7 Yes     1.52
Muestra1[,-2]           # E) Todas las filas, pero sin la columna 2 (por eso, el signo menos)
## # A tibble: 10 × 5
##    ID               Like      Age Smoke Height
##    <chr>            <chr>   <dbl> <chr>  <dbl>
##  1 SB11201910010435 TV       21.4 No      1.58
##  2 SB11201910004475 Network  21.1 Yes     1.6 
##  3 SB11201910011427 Network  20.9 Yes     1.5 
##  4 SB11201910041975 TV       18.4 Yes     1.53
##  5 SB11201910013623 TV       16.6 Yes     1.78
##  6 SB11201910038122 Network  16.0 No      1.65
##  7 SB11201910037905 TV       19.3 Yes     1.73
##  8 SB11201910038140 TV       18.6 Yes     1.53
##  9 SB11201910038005 TV       17.0 Yes     1.64
## 10 SB11201910037919 TV       19.7 Yes     1.52
Muestra1[,2:5]          # F) Todas las filas, pero solo columnas de 2 a 5 (por eso, dos puntos)
## # A tibble: 10 × 4
##    Gender Like      Age Smoke
##    <chr>  <chr>   <dbl> <chr>
##  1 Female TV       21.4 No   
##  2 Male   Network  21.1 Yes  
##  3 Male   Network  20.9 Yes  
##  4 Male   TV       18.4 Yes  
##  5 Female TV       16.6 Yes  
##  6 Female Network  16.0 No   
##  7 Female TV       19.3 Yes  
##  8 Female TV       18.6 Yes  
##  9 Female TV       17.0 Yes  
## 10 Male   TV       19.7 Yes
Muestra1[,c(2,5)]       # G) Todas las filas, pero solo columnas 2 y 5 (*c* representa un vector)
## # A tibble: 10 × 2
##    Gender Smoke
##    <chr>  <chr>
##  1 Female No   
##  2 Male   Yes  
##  3 Male   Yes  
##  4 Male   Yes  
##  5 Female Yes  
##  6 Female No   
##  7 Female Yes  
##  8 Female Yes  
##  9 Female Yes  
## 10 Male   Yes
Muestra1[1:4,2:5]       # H) Solo las filas de 1 a 4, con las columnas 2 a 5 
## # A tibble: 4 × 4
##   Gender Like      Age Smoke
##   <chr>  <chr>   <dbl> <chr>
## 1 Female TV       21.4 No   
## 2 Male   Network  21.1 Yes  
## 3 Male   Network  20.9 Yes  
## 4 Male   TV       18.4 Yes
Muestra1[1:4,c(2,5)]         # I) Solo las filas de 1 a 4, con las columnas 2 y 5 
## # A tibble: 4 × 2
##   Gender Smoke
##   <chr>  <chr>
## 1 Female No   
## 2 Male   Yes  
## 3 Male   Yes  
## 4 Male   Yes
Muestra1[c(1,5),c(2,4, 6:6)] # J) Solo las filas 1 y 5, con las columnas 2, 4 y desde 6 a 8
## # A tibble: 2 × 3
##   Gender   Age Height
##   <chr>  <dbl>  <dbl>
## 1 Female  21.4   1.58
## 2 Female  16.6   1.78
Muestra1[1:5,-c(2,5)]        # K) Solo las filas de 1 a 5, quitando las columnas 2 y 5 
## # A tibble: 5 × 4
##   ID               Like      Age Height
##   <chr>            <chr>   <dbl>  <dbl>
## 1 SB11201910010435 TV       21.4   1.58
## 2 SB11201910004475 Network  21.1   1.6 
## 3 SB11201910011427 Network  20.9   1.5 
## 4 SB11201910041975 TV       18.4   1.53
## 5 SB11201910013623 TV       16.6   1.78
Muestra1[-3,-c(2,5)]         # L) Quitar la filas 3, y las columnas 2 y 5 
## # A tibble: 9 × 4
##   ID               Like      Age Height
##   <chr>            <chr>   <dbl>  <dbl>
## 1 SB11201910010435 TV       21.4   1.58
## 2 SB11201910004475 Network  21.1   1.6 
## 3 SB11201910041975 TV       18.4   1.53
## 4 SB11201910013623 TV       16.6   1.78
## 5 SB11201910038122 Network  16.0   1.65
## 6 SB11201910037905 TV       19.3   1.73
## 7 SB11201910038140 TV       18.6   1.53
## 8 SB11201910038005 TV       17.0   1.64
## 9 SB11201910037919 TV       19.7   1.52

6 Tipos de variables

Objetivo

En esta sección se identifican los diferentes tipos de variables que contiene el data frame datosCompleto. Primero se revisa su estructura para conocer el tipo de dato de cada variable.

Código

str(datosCompleto)   #A) Estructura de los datos
## tibble [800 × 66] (S3: tbl_df/tbl/data.frame)
##  $ Observation : num [1:800] 1 2 3 4 5 6 7 8 9 10 ...
##  $ ID          : chr [1:800] "SB11201910010435" "SB11201910004475" "SB11201910011427" "SB11201910041975" ...
##  $ Gender      : chr [1:800] "Female" "Male" "Male" "Male" ...
##  $ Like        : chr [1:800] "TV" "Network" "Network" "TV" ...
##  $ Age         : num [1:800] 21.4 21.1 20.9 18.4 16.6 ...
##  $ Smoke       : chr [1:800] "No" "Yes" "Yes" "Yes" ...
##  $ Height      : num [1:800] 1.58 1.6 1.5 1.53 1.78 1.65 1.73 1.53 1.64 1.52 ...
##  $ Weight      : num [1:800] 75 80 64 49 82 80 90 55 50 78 ...
##  $ BMI         : num [1:800] 30 31.2 28.4 20.9 25.9 ...
##  $ School      : chr [1:800] "Private" "Public" "Private" "Public" ...
##  $ SES         : chr [1:800] "Medium" "High" "High" "Low" ...
##  $ Enrollment  : chr [1:800] "Credit" "Scholarship" "Scholarship" "Credit" ...
##  $ Score       : num [1:800] 81 78 77 70 68 65 54 50 36 35 ...
##  $ MotherHeight: chr [1:800] "Short_M" "Normal_M" "Normal_M" "Tall_M" ...
##  $ MotherAge   : num [1:800] 41 45 45 45 46 46 47 48 48 48 ...
##  $ MotherCHD   : num [1:800] 0 0 0 0 1 0 0 0 0 1 ...
##  $ FatherHeight: chr [1:800] "Normal_F" "Short_F" "Tall_F" "Short_F" ...
##  $ FatherAge   : num [1:800] 40 43 44 45 45 46 46 48 48 49 ...
##  $ FatherCHD   : num [1:800] 1 1 1 2 1 1 1 1 1 1 ...
##  $ Status      : chr [1:800] "Distinguished" "Distinguished" "Distinguished" "Regular" ...
##  $ SemAcum     : num [1:800] 4.25 2.8 4.15 3.2 3.45 2.75 2.7 4.35 4.3 2.8 ...
##  $ Exam1       : num [1:800] 1.5 2.3 3.4 2.5 3.1 3.8 5 4 2.5 2.4 ...
##  $ Exam2       : num [1:800] 5 4.9 3.6 4.2 3.5 4.4 3 2.3 3.3 2.6 ...
##  $ Exam3       : num [1:800] 5 3.7 2 5 5 4.2 3.5 4.6 3.8 4.3 ...
##  $ Exam4       : num [1:800] 4.5 3.3 1.9 2.5 3 5 3.6 4.3 1.9 5 ...
##  $ ExamAcum    : num [1:800] 16 14.2 10.9 14.2 14.6 17.4 15.1 15.2 11.5 14.3 ...
##  $ Definitive  : num [1:800] 4 3.55 2.73 3.55 3.65 ...
##  $ Expense     : num [1:800] 48.9 72.1 85.2 56.6 64.6 63 40.8 65.4 37.3 63 ...
##  $ Income      : num [1:800] 1.61 2.07 2.84 1.55 2.32 2.1 1.69 2.18 1.71 2.1 ...
##  $ Gas         : num [1:800] 27.4 24.2 22.3 23.1 27.3 ...
##  $ Course      : chr [1:800] "Face-to-Face" "Virtual" "Face-to-Face" "Virtual" ...
##  $ Law         : chr [1:800] "Agree" "Agree" "Agree" "Agree" ...
##  $ Economic    : chr [1:800] "Regular" "Good" "Regular" "Bad" ...
##  $ Race        : chr [1:800] "Ethnic" "Ethnic" "Ethnic" "Ethnic" ...
##  $ Region      : chr [1:800] "North" "Center" "North" "Center" ...
##  $ EMO1        : num [1:800] 1 4 3 4 2 3 2 3 4 2 ...
##  $ EMO2        : num [1:800] 2 4 1 2 1 1 4 1 2 2 ...
##  $ EMO3        : num [1:800] 2 1 3 3 2 4 2 4 3 3 ...
##  $ EMO4        : num [1:800] 1 2 3 1 4 2 3 2 1 1 ...
##  $ EMO5        : num [1:800] 4 1 2 2 2 2 1 1 2 2 ...
##  $ GOAL1       : chr [1:800] "Strongly agree" "Undecided" "Agree" "Agree" ...
##  $ GOAL2       : chr [1:800] "Agree" "Disagree" "Disagree" "Undecided" ...
##  $ GOAL3       : chr [1:800] "Strongly agree" "Disagree" "Agree" "Strongly agree" ...
##  $ Pre_STAT1   : num [1:800] 2 1 5 4 1 4 4 2 2 2 ...
##  $ Pre_STAT2   : num [1:800] 4 1 1 3 4 1 2 3 3 5 ...
##  $ Pre_STAT3   : num [1:800] 2 1 3 1 1 5 4 3 3 2 ...
##  $ Pre_STAT4   : num [1:800] 5 1 1 2 2 3 2 3 2 4 ...
##  $ Post_STAT1  : num [1:800] 4 5 5 3 5 2 3 3 2 5 ...
##  $ Post_STAT2  : num [1:800] 5 1 2 2 3 3 2 3 2 3 ...
##  $ Post_STAT3  : num [1:800] 2 3 3 4 3 5 5 4 5 4 ...
##  $ Post_STAT4  : num [1:800] 2 3 3 5 4 4 3 5 5 1 ...
##  $ Pre_IDARE1  : chr [1:800] "Quite a bit" "Quite a bit" "Quite a bit" "Little" ...
##  $ Pre_IDARE2  : chr [1:800] "Little" "Little" "Little" "Nothing" ...
##  $ Pre_IDARE3  : chr [1:800] "Quite a bit" "A lot" "Quite a bit" "Quite a bit" ...
##  $ Pre_IDARE4  : chr [1:800] "Quite a bit" "Nothing" "Quite a bit" "Quite a bit" ...
##  $ Pre_IDARE5  : chr [1:800] "Little" "Quite a bit" "Little" "Nothing" ...
##  $ Post_IDARE1 : chr [1:800] "A lot" "A little" "Nothing" "Quite a bit" ...
##  $ Post_IDARE2 : chr [1:800] "A lot" "Nothing" "Quite a bit" "A little" ...
##  $ Post_IDARE3 : chr [1:800] "A little" "Quite a bit" "Nothing" "A lot" ...
##  $ Post_IDARE4 : chr [1:800] "Quite a bit" "A lot" "Nothing" "Quite a bit" ...
##  $ Post_IDARE5 : chr [1:800] "A lot" "Quite a bit" "Nothing" "A lot" ...
##  $ PSICO1      : chr [1:800] "Frequently" "Frequently" "Sometimes" "Almost always" ...
##  $ PSICO2      : chr [1:800] "Almost always" "Sometimes" "Sometimes" "Frequently" ...
##  $ PSICO3      : chr [1:800] "Frequently" "Sometimes" "Sometimes" "Frequently" ...
##  $ PSICO4      : chr [1:800] "Almost always" "Frequently" "Frequently" "Almost never" ...
##  $ PSICO5      : chr [1:800] "Almost always" "Frequently" "Sometimes" "Sometimes" ...

6.0.1 Nominales o carácter

Objetivo

En este apartado se identifican algunas variables de la base datosCompleto y se asignan a nuevos objetos. Se revisa cómo R interpreta estas variables y se determina si su tipo de dato es adecuado.

Código

Codigo <- datosCompleto$ID     #B) Si es tipo caracter, es correcto)
Edad <- datosCompleto$Age      #C) Si es tipo caracter, es incorrecto (ver ejemplo 4) 
Sexo <- datosCompleto$Gender   #D) Si es tipo caracter, es incorrecto (ver ejemplo 5)

Salida

Los objetos Codigo, Edad y Sexo contienen respectivamente la información de las variables ID, Age y Gender de la base de datos datosCompleto.

Interpretación

La variable Codigo corresponde al identificador de cada estudiante y puede ser tratada como una variable de carácter. En cambio, Edad representa la edad y Sexo representa una categoría, por lo que debemos verificar que R las haya reconocido con el tipo de dato adecuado antes de realizar análisis estadísticos.

6.0.2 Numéricas

Objetivo

En este apartado se identifican variables numéricas de la base datosCompleto. Se seleccionan las variables correspondientes al primer examen, segundo examen y edad para utilizarlas posteriormente en los análisis estadísticos.

Código

P1   <- datosCompleto$Exam1 #E) Numérica
P2   <- datosCompleto$Exam2 #F) Numérica
Edad <- datosCompleto$Age   #G) Numérica

6.0.3 Categórica o factor

Objetivo

En este apartado se convierte la variable Sexo en una variable categórica de tipo factor. Esto permite que R reconozca que los valores de Sexo corresponden a diferentes categorías.

Código

Sexo <- as.factor(Sexo)  #H) Convirtiendo a factor
class(Sexo)              #I) Sale: "factor"
## [1] "factor"
str(Sexo)                #J) Sale: Factor w/ 2 levels "Female","Masculino": 1 2 2 2 1 1 1 1 1 2 ...
##  Factor w/ 2 levels "Female","Male": 1 2 2 2 1 1 1 1 1 2 ...
levels(Sexo)             #K) Sale: "Female"  "Masculino"
## [1] "Female" "Male"

Salida

La función class() muestra que Sexo es de tipo factor.

La función str() muestra que la variable es un factor con 2 niveles: "Female" y "Masculino".

La función levels() muestra las categorías:

[1] "Female" "Masculino"

Interpretación

Al convertir Sexo mediante as.factor(), R reconoce esta variable como categórica. En este caso existen dos categorías: Female y Masculino. Esto permite trabajar correctamente con la variable en análisis estadísticos que requieren variables categóricas.

7.0.1 Tablas univariadas

Objetivo

En esta sección se construyen tablas de frecuencias para analizar la distribución de variables categóricas. Se utiliza una muestra de las primeras 100 observaciones de datosCompleto y se analizan las variables Sexo y Fuma.

Código

Muestra <- datosCompleto[1:100,]

#A) Definiendo y convirtiendo en factor
Sexo <- as.factor(Muestra$Gender)  

#B) Calcular tabla de frecuencias
Tabla1 <- table(Sexo)
Tabla1                 
## Sexo
## Female   Male 
##     49     51
#Porcentaje de Mujeres 

(49/100)*100
## [1] 49
Fuma <- as.factor(Muestra$Smoke) 
#B) Tabla de frecuencias 
Tabla3 <- table(Sexo, Fuma)
Tabla3     
##         Fuma
## Sexo     No Yes
##   Female 21  28
##   Male   24  27
(28/55)*100
## [1] 50.90909

Interpretación

El 50.9% de mujeres hace parte dentro del grupo de Fumadores.

##8.0 Diagrama de Barras

ggplot(Muestra, aes(x = Sexo)) +                            #1
  #geom_bar() +                                             #2
  geom_bar(width=0.5, colour="hotpink1", fill="skyblue") +       #2 
  
  labs(x="Sexo",y= "Frecuencia")  +              #3               
  ylim(c(0,60)) +                               #4
  #xlim(c(0,300)) +                              #4
  ggtitle("Diagrama de barras")  +               #5
  
  # theme_bw() +                                 #6
  theme_bw(base_size = 12) +                     #6
  #coord_flip() +                                #7
  
  geom_text(aes(label=..count..), stat='count',  #8
            position=position_dodge(0.9), 
            vjust=-0.5, 
            size=5.0
            ) + 
  facet_wrap(~"Variable Sexo")                   #9
## Warning: The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(count)` instead.
## This warning is displayed once per session.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

9.0 DIAGRAMA DE BARRAS (CASO BIVARIADO)

ggplot(Muestra, aes(Fuma,  fill=Sexo)) +      #1
  geom_bar()+                                          #2
  
  labs(x= "Fuma",  y="Frecuencias", fill="Sexo") +  #3 
  
  ylim(c(0,60))  +                  #4   
  #xlim(c(0,300)) +                  #4
  
  ggtitle("Diagrama de barras") +    #5
  #coord_flip() +                    #6
  #theme_bw() +                      #7
  theme_bw(base_size = 12)           #7

9.0.2 Ejemplo 3 (Otra forma de construir el mismo diagrama)

ggplot(Muestra, aes(Sexo,  fill=Fuma)) +      
  geom_bar(position="dodge",colour="black") +
  
  labs(x= "Sexo",  y="Frecuencias", fill="Fuma") +
  ylim(c(0,30)) +
  #xlim(c(0,300)) +   
  
  ggtitle("Diagrama de barras") + 
  
  #theme_bw() +                     
  theme_bw(base_size = 12) +          
  #coord_flip() + 
  
  #guides(fill=FALSE)+                                #8                                    
  scale_fill_manual(values = c("hotpink1","lightskyblue1")) +   #9
  
  geom_text(aes(label=..count..), stat='count',       #10
            position=position_dodge(0.9),
            vjust=-0.5, 
            size=5.0
            )+
  
  facet_wrap(~"fuma por Generos")  #11

(21/49)*100
## [1] 42.85714

Interpretación:

El 42.8% de Mujeres hace parte del grupo de no fumadores.

10.0.1 Ejemplo 5 (dentro de mujeres: Estatura versus Fuma)

Muestra %>% filter(Gender=="Female") %>%    #12
  
ggplot(., aes(Smoke,  fill=MotherHeight)) + 
  geom_bar(position="dodge",colour="black") +
  
  labs(x= "Fuma", y="Frecuencias", fill="Estatura") +
  ylim(c(0,15)) +
  #xlim(c(0,300)) + 
  
  ggtitle("Diagrama de barras en el grupo de las mujeres") +   
  #theme_bw() + 
  theme_bw(base_size = 14) +
  #coord_flip() +
  
  #guides(fill=FALSE)+
  #scale_fill_manual(values = c("lightpink","peachpuff1", "navajowhite1")) +
  
  geom_text(aes(label=..count..),stat='count',
            position=position_dodge(0.9),
            vjust=-0.5, 
            size=5.0) +
  
  facet_wrap(~"Estatura por fumadores y no fumadores")

### 10.0.2 Ejemplo 6 (dentro de hombres: Estatura versus Fuma)

Muestra %>% filter(Gender=="Male") %>%    #13
  
ggplot(., aes(Smoke,  fill=MotherHeight)) + 
  geom_bar(position="dodge",colour="black") +
  
  labs(x= "Fuma", y="Frecuencias", fill="Estatura") +
  ylim(c(0,15))+
  #xlim(c(0,300)) + 
  
  ggtitle("Diagrama de barras en el grupo de los hombres") +   
  #theme_bw() + 
  theme_bw(base_size = 14) +
  #coord_flip() +
  
  #guides(fill=FALSE) +
  scale_fill_manual(values = c("red","blue", "green"))+
  geom_text(aes(label=..count..),stat='count',
            position=position_dodge(0.9),
            vjust=-0.5, 
            size=5.0) +
  
  facet_wrap(~"Estatura por fumadores y no fumadores")

## 11 Diagrama de barras (caso bivariado): tercer caso

11.0.1 Ejemplo 7 (construyendo, primero, una tabla cruzada)

Tabla <- Muestra %>%
  dplyr::group_by(Smoke, Gender) %>%                               #14
  dplyr::summarise(Total = n()) %>%                                #15
  dplyr::mutate(Porcentaje = round(Total/sum(Total)*100, 1)) %>%   #16
  
  dplyr::arrange(Smoke)                                            #17
## `summarise()` has regrouped the output.
## ℹ Summaries were computed grouped by Smoke and Gender.
## ℹ Output is grouped by Smoke.
## ℹ Use `summarise(.groups = "drop_last")` to silence this message.
## ℹ Use `summarise(.by = c(Smoke, Gender))` for per-operation grouping
##   (`?dplyr::dplyr_by`) instead.
  #dplyr::arrange(desc(Fuma))                                      #17  
  #dplyr::arrange(Sexo)                                            #17
  #dplyr::arrange(desc(Sexo))                                      #17
Tabla
## # A tibble: 4 × 4
## # Groups:   Smoke [2]
##   Smoke Gender Total Porcentaje
##   <chr> <chr>  <int>      <dbl>
## 1 No    Female    21       46.7
## 2 No    Male      24       53.3
## 3 Yes   Female    28       50.9
## 4 Yes   Male      27       49.1

Diagrama

ggplot(Tabla, aes(x = Smoke, y=Total, fill=Gender) ) + 
  geom_bar(width = 0.9,stat="identity",                 #18
              position = position_dodge()               #19  
           ) +  
  ylim(c(0,40))+
  #xlim(c(0,300)) +                  
  #ggtitle("Un título") + 
  labs(x="Fuma", y= "Frecuencias \n (Porcentajes)") +   #20
  labs(fill = "Sexo") +                                 #21
  
  scale_fill_manual(values = c("pink",  "skyblue")) +   #22
  
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),  #23
            vjust=-0.9, 
            color="black", 
            hjust=0.5,
            # define text position and size
            position = position_dodge(0.9),  
            angle=0, 
            size=4.0
            )+
  
  scale_fill_discrete(name = "Sexo", labels = c("Mujer", "Hombre")) +     #24
  
  theme(axis.text.x = element_text(angle = 0, vjust = 1, hjust=1)) +      #25
  theme_bw(base_size = 14) +
  #coord_flip() +                                                         #26
  facet_wrap(~"Sexo versus Fuma")
## Scale for fill is already present.
## Adding another scale for fill, which will replace the existing scale.

###11.0.2 Ejemplo 9 (con tabla cruzada y coord_flip)

ggplot(Tabla, aes(x = Smoke, y=Total, fill=Gender) ) + 
  geom_bar(width = 0.9,stat="identity",                 
              position = position_dodge()                 
           ) +  
  ylim(c(0,50))+
  #xlim(c(0,300)) +                  
  
  #ggtitle("Un título") + 
  
  labs(x="Fuma", y= "Frecuencias \n (Porcentajes)") +   
  labs(fill = "Sexo") +                                 
  
  scale_fill_manual(values = c("pink",  "skyblue")) +   
  
  geom_text(aes(label=paste0(Total," ", "", "(", Porcentaje, "%", ")")),        #27
            #vjust=-0.9,                       #28
            color="black",                     #29
            hjust=-0.15,                       #30   
            # define text position and size    #31
            position = position_dodge(0.9),    #32
            angle=90,                          #33
            size=4.0                           #34
            )+
  
  scale_fill_discrete(name = "Sexo", labels = c("Female", "Male")) +          #35
  
  theme(axis.text.x = element_text(angle = 45,   #36
                                   vjust = 1,    #37
                                   hjust=1,      #38
                                   size=14)      #39
        ) +    
  #theme_bw(base_size = 14) +
  #coord_flip() +
  facet_wrap(~"Sexo versus Fuma") 
## Scale for fill is already present.
## Adding another scale for fill, which will replace the existing scale.

###12.0.1 Ejemplo 10: position_stack(reverse = FALSE)}

Muestra %>% filter(Gender=="Female") %>%    
  
ggplot(., aes(Smoke)) + 
  
  geom_bar(aes(fill = MotherHeight),                        #40
           #position = position_stack(reverse = TRUE),  #41
           colour="brown"                               #42
           ) +
  
  labs(x= "Fuma", y="Frecuencias", fill="Estatura") +
  ylim(c(0,40))+
  #xlim(c(0,300)) + 
  
  ggtitle("Diagrama de barras en el grupo de los hombres") +   
  #theme_bw() + 
  theme_bw(base_size = 14) +
  theme(legend.position = "top") +   #43
  
  coord_flip() +                     #44
  
  #guides(fill=FALSE) +
  scale_fill_manual(values = c("red","blue", "green"))+
  geom_text(aes(label=..count..),stat='count',
            position=position_dodge(0.9),
            hjust=-0.6, 
            size=5.0) +
  
  facet_wrap(~"Estatura por fumadores y no fumadores")

###12.0.2 Ejemplo 11: position_stack(reverse = TRUE)

Muestra %>% filter(Gender=="Female") %>%    
  
ggplot(., aes(Smoke)) + 
  
  geom_bar(aes(fill = MotherHeight),                        #44
           position = position_stack(reverse = TRUE),   #45
           colour="brown"                               #46
           ) +
  
  labs(x= "Fuma", y="Frecuencias", fill="Estatura") +
  ylim(c(0,40))+
  #xlim(c(0,300)) + 
  
  ggtitle("Diagrama de barras en el grupo de los hombres") +   
  #theme_bw() + 
  theme_bw(base_size = 14) +
  theme(legend.position = "top") +   #47
  
  coord_flip() +                     #48
  
  #guides(fill=FALSE) +
  scale_fill_manual(values = c("red","blue", "green"))+
  geom_text(aes(label=..count..),stat='count',
            position=position_dodge(0.9),
            hjust=-0.6, 
            size=5.0) +
  
  facet_wrap(~"Estatura por fumadores y no fumadores")

Estructura de la Muestra

str(Muestra)
## tibble [100 × 66] (S3: tbl_df/tbl/data.frame)
##  $ Observation : num [1:100] 1 2 3 4 5 6 7 8 9 10 ...
##  $ ID          : chr [1:100] "SB11201910010435" "SB11201910004475" "SB11201910011427" "SB11201910041975" ...
##  $ Gender      : chr [1:100] "Female" "Male" "Male" "Male" ...
##  $ Like        : chr [1:100] "TV" "Network" "Network" "TV" ...
##  $ Age         : num [1:100] 21.4 21.1 20.9 18.4 16.6 ...
##  $ Smoke       : chr [1:100] "No" "Yes" "Yes" "Yes" ...
##  $ Height      : num [1:100] 1.58 1.6 1.5 1.53 1.78 1.65 1.73 1.53 1.64 1.52 ...
##  $ Weight      : num [1:100] 75 80 64 49 82 80 90 55 50 78 ...
##  $ BMI         : num [1:100] 30 31.2 28.4 20.9 25.9 ...
##  $ School      : chr [1:100] "Private" "Public" "Private" "Public" ...
##  $ SES         : chr [1:100] "Medium" "High" "High" "Low" ...
##  $ Enrollment  : chr [1:100] "Credit" "Scholarship" "Scholarship" "Credit" ...
##  $ Score       : num [1:100] 81 78 77 70 68 65 54 50 36 35 ...
##  $ MotherHeight: chr [1:100] "Short_M" "Normal_M" "Normal_M" "Tall_M" ...
##  $ MotherAge   : num [1:100] 41 45 45 45 46 46 47 48 48 48 ...
##  $ MotherCHD   : num [1:100] 0 0 0 0 1 0 0 0 0 1 ...
##  $ FatherHeight: chr [1:100] "Normal_F" "Short_F" "Tall_F" "Short_F" ...
##  $ FatherAge   : num [1:100] 40 43 44 45 45 46 46 48 48 49 ...
##  $ FatherCHD   : num [1:100] 1 1 1 2 1 1 1 1 1 1 ...
##  $ Status      : chr [1:100] "Distinguished" "Distinguished" "Distinguished" "Regular" ...
##  $ SemAcum     : num [1:100] 4.25 2.8 4.15 3.2 3.45 2.75 2.7 4.35 4.3 2.8 ...
##  $ Exam1       : num [1:100] 1.5 2.3 3.4 2.5 3.1 3.8 5 4 2.5 2.4 ...
##  $ Exam2       : num [1:100] 5 4.9 3.6 4.2 3.5 4.4 3 2.3 3.3 2.6 ...
##  $ Exam3       : num [1:100] 5 3.7 2 5 5 4.2 3.5 4.6 3.8 4.3 ...
##  $ Exam4       : num [1:100] 4.5 3.3 1.9 2.5 3 5 3.6 4.3 1.9 5 ...
##  $ ExamAcum    : num [1:100] 16 14.2 10.9 14.2 14.6 17.4 15.1 15.2 11.5 14.3 ...
##  $ Definitive  : num [1:100] 4 3.55 2.73 3.55 3.65 ...
##  $ Expense     : num [1:100] 48.9 72.1 85.2 56.6 64.6 63 40.8 65.4 37.3 63 ...
##  $ Income      : num [1:100] 1.61 2.07 2.84 1.55 2.32 2.1 1.69 2.18 1.71 2.1 ...
##  $ Gas         : num [1:100] 27.4 24.2 22.3 23.1 27.3 ...
##  $ Course      : chr [1:100] "Face-to-Face" "Virtual" "Face-to-Face" "Virtual" ...
##  $ Law         : chr [1:100] "Agree" "Agree" "Agree" "Agree" ...
##  $ Economic    : chr [1:100] "Regular" "Good" "Regular" "Bad" ...
##  $ Race        : chr [1:100] "Ethnic" "Ethnic" "Ethnic" "Ethnic" ...
##  $ Region      : chr [1:100] "North" "Center" "North" "Center" ...
##  $ EMO1        : num [1:100] 1 4 3 4 2 3 2 3 4 2 ...
##  $ EMO2        : num [1:100] 2 4 1 2 1 1 4 1 2 2 ...
##  $ EMO3        : num [1:100] 2 1 3 3 2 4 2 4 3 3 ...
##  $ EMO4        : num [1:100] 1 2 3 1 4 2 3 2 1 1 ...
##  $ EMO5        : num [1:100] 4 1 2 2 2 2 1 1 2 2 ...
##  $ GOAL1       : chr [1:100] "Strongly agree" "Undecided" "Agree" "Agree" ...
##  $ GOAL2       : chr [1:100] "Agree" "Disagree" "Disagree" "Undecided" ...
##  $ GOAL3       : chr [1:100] "Strongly agree" "Disagree" "Agree" "Strongly agree" ...
##  $ Pre_STAT1   : num [1:100] 2 1 5 4 1 4 4 2 2 2 ...
##  $ Pre_STAT2   : num [1:100] 4 1 1 3 4 1 2 3 3 5 ...
##  $ Pre_STAT3   : num [1:100] 2 1 3 1 1 5 4 3 3 2 ...
##  $ Pre_STAT4   : num [1:100] 5 1 1 2 2 3 2 3 2 4 ...
##  $ Post_STAT1  : num [1:100] 4 5 5 3 5 2 3 3 2 5 ...
##  $ Post_STAT2  : num [1:100] 5 1 2 2 3 3 2 3 2 3 ...
##  $ Post_STAT3  : num [1:100] 2 3 3 4 3 5 5 4 5 4 ...
##  $ Post_STAT4  : num [1:100] 2 3 3 5 4 4 3 5 5 1 ...
##  $ Pre_IDARE1  : chr [1:100] "Quite a bit" "Quite a bit" "Quite a bit" "Little" ...
##  $ Pre_IDARE2  : chr [1:100] "Little" "Little" "Little" "Nothing" ...
##  $ Pre_IDARE3  : chr [1:100] "Quite a bit" "A lot" "Quite a bit" "Quite a bit" ...
##  $ Pre_IDARE4  : chr [1:100] "Quite a bit" "Nothing" "Quite a bit" "Quite a bit" ...
##  $ Pre_IDARE5  : chr [1:100] "Little" "Quite a bit" "Little" "Nothing" ...
##  $ Post_IDARE1 : chr [1:100] "A lot" "A little" "Nothing" "Quite a bit" ...
##  $ Post_IDARE2 : chr [1:100] "A lot" "Nothing" "Quite a bit" "A little" ...
##  $ Post_IDARE3 : chr [1:100] "A little" "Quite a bit" "Nothing" "A lot" ...
##  $ Post_IDARE4 : chr [1:100] "Quite a bit" "A lot" "Nothing" "Quite a bit" ...
##  $ Post_IDARE5 : chr [1:100] "A lot" "Quite a bit" "Nothing" "A lot" ...
##  $ PSICO1      : chr [1:100] "Frequently" "Frequently" "Sometimes" "Almost always" ...
##  $ PSICO2      : chr [1:100] "Almost always" "Sometimes" "Sometimes" "Frequently" ...
##  $ PSICO3      : chr [1:100] "Frequently" "Sometimes" "Sometimes" "Frequently" ...
##  $ PSICO4      : chr [1:100] "Almost always" "Frequently" "Frequently" "Almost never" ...
##  $ PSICO5      : chr [1:100] "Almost always" "Frequently" "Sometimes" "Sometimes" ...

13.Medidas estadísticas

##13.0.1 Caso 1

Muestra2 <- datosCompleto[1:100,] 
x <- as.numeric(Muestra2$Exam3)  # A) Convirtiendo la variable a numérica
x
##   [1] 5.0 3.7 2.0 5.0 5.0 4.2 3.5 4.6 3.8 4.3 3.0 3.8 3.4 3.3 3.5 4.5 3.6 4.0
##  [19] 3.4 4.0 4.2 3.5 3.7 4.0 4.0 3.2 2.9 2.9 3.0 3.3 2.8 2.4 3.8 3.3 3.2 2.2
##  [37] 2.6 3.2 3.3 1.2 4.2 2.4 5.0 2.8 3.0 3.8 3.2 1.5 2.6 3.8 3.2 3.3 1.4 3.8
##  [55] 1.4 3.6 3.6 2.4 2.8 3.1 2.4 1.8 1.6 3.3 4.4 1.0 4.5 2.0 4.2 4.2 3.1 2.3
##  [73] 2.6 2.7 2.4 2.2 2.8 2.4 1.9 2.4 1.7 2.9 2.4 2.2 2.8 3.2 3.1 2.7 2.5 3.5
##  [91] 3.3 2.1 3.3 2.1 3.7 5.0 3.7 2.0 5.0 5.0
min(x)          #B) Mínimo
## [1] 1
max(x)          #C) Máximo
## [1] 5
range(x)        #D) Obtenemos (min, max)
## [1] 1 5
length(x)       #E) Tamaño
## [1] 100
sum(x)          #F) Suma los valores de los datos
## [1] 317.6
mean(x)         #G) Media aritmética
## [1] 3.176
median(x)       #H) Mediana
## [1] 3.2
var(x)          #I) Varianza muestral
## [1] 0.8885091
sqrt(var(x))    #J) Desviación estándar muestral (una forma)
## [1] 0.9426076
sd(x)           #K) Desviación estándar muestral (otra forma)
## [1] 0.9426076
skewness(x)     #L) Sesgo
## [1] 0.01846742
quantile(x, probs=0.80)    #M) 80-ésimo percentil o percentil 85
## 80% 
##   4
quantile(x, probs=0.25)    #N) Primer cuartil o 25-ésimo percentil
## 25% 
## 2.4
quantile(x, probs=0.50)    #O) Segundo cuartil o 50-ésimo percentil o mediana
## 50% 
## 3.2
quantile(x, probs=0.75)    #P) Tercer cuartil o 75-ésimo percentil
## 75% 
## 3.8

Interpretación

El 50% de las notas del Examen 3° es menor o igual que 3.2 La varianza y la desviación no se interpretran. El Sesgo es Positivo. El 80% de los estudiantes saco una nota menor o igual que 4.0

quantile(x, probs=0.85, na.rm = TRUE)    #M) 80-ésimo percentil o percentil 85
## 85% 
## 4.2

INTERPRETACIÓN:

El 85% de los estudiantes sacaron menos o igual a 4.2