Instalamos paquetes y cargamos las librerias

#install.packages("devtools")
#install.packages("dplyr")
#install.packages("rmarkdown")
#install.packages("ggplot2")
#install.packages("broom")
#install.packages("gridExtra")
#install.packages("shiny")
#install.packages("cubature")
#install.packages("tidyr")

Más instalaciones

library(devtools)
## Loading required package: usethis
install_github("StatsWithR/statsr")
## Skipping install of 'statsr' from a github remote, the SHA1 (9cb9edad) has not changed since last install.
##   Use `force = TRUE` to force installation
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)
library(statsr)
## Loading required package: BayesFactor
## Loading required package: coda
## Loading required package: Matrix
## ************
## Welcome to BayesFactor 0.9.12-4.7. If you have questions, please contact Richard Morey (richarddmorey@gmail.com).
## 
## Type BFManual() to open the manual.
## ************

Para cargar los datos

data("arbuthnot")

The Arbuthnot data set refers to Dr. John Arbuthnot, an 18th century physician, writer, and mathematician. He was interested in the ratio of newborn boys to newborn girls, so he gathered the baptism records for children born in London for every year from 1629 to 1710. We can take a look at the data by typing its name into the console.

Para ver los datos y la dimensión

dim(arbuthnot)
## [1] 82  3

Para ver todos los datos

arbuthnot
## # A tibble: 82 × 3
##     year  boys girls
##    <int> <int> <int>
##  1  1629  5218  4683
##  2  1630  4858  4457
##  3  1631  4422  4102
##  4  1632  4994  4590
##  5  1633  5158  4839
##  6  1634  5035  4820
##  7  1635  5106  4928
##  8  1636  4917  4605
##  9  1637  4703  4457
## 10  1638  5359  4952
## # ℹ 72 more rows

Para ver los nombres de las columnas (o variables)

names(arbuthnot)
## [1] "year"  "boys"  "girls"

1. How many variables are included in this data set?

Exercise: What years are included in this dataset? La respuesta es 3

Podemos acceder a los datos de una sola columna del data frame con el siguiente comando. Esto solo muestra el número de niños bautizados cada año.

arbuthnot$boys
##  [1] 5218 4858 4422 4994 5158 5035 5106 4917 4703 5359 5366 5518 5470 5460 4793
## [16] 4107 4047 3768 3796 3363 3079 2890 3231 3220 3196 3441 3655 3668 3396 3157
## [31] 3209 3724 4748 5216 5411 6041 5114 4678 5616 6073 6506 6278 6449 6443 6073
## [46] 6113 6058 6552 6423 6568 6247 6548 6822 6909 7577 7575 7484 7575 7737 7487
## [61] 7604 7909 7662 7602 7676 6985 7263 7632 8062 8426 7911 7578 8102 8031 7765
## [76] 6113 8366 7952 8379 8239 7840 7640

What command would you use to extract just the counts of girls born?

  1. arbuthnot$boys
  2. arbuthnot$girls
  3. girls
  4. arbuthnot[girls]
  5. $girls

La respuesta es arbuthnot$girls

arbuthnot$girls
##  [1] 4683 4457 4102 4590 4839 4820 4928 4605 4457 4952 4784 5332 5200 4910 4617
## [16] 3997 3919 3395 3536 3181 2746 2722 2840 2908 2959 3179 3349 3382 3289 3013
## [31] 2781 3247 4107 4803 4881 5681 4858 4319 5322 5560 5829 5719 6061 6120 5822
## [46] 5738 5717 5847 6203 6033 6041 6299 6533 6744 7158 7127 7246 7119 7214 7101
## [61] 7167 7302 7392 7316 7483 6647 6713 7229 7767 7626 7452 7061 7514 7656 7683
## [76] 5738 7779 7417 7687 7623 7380 7288

Podemos realizar una gráfica para mostrar el número de niñas bautizadas en función del año

ggplot(data = arbuthnot, aes(x = year, y = girls)) +
  geom_point()

Podemos crear una nueva variable (total = suma de niños y niñas) en una nueva columna con la función mutate

arbuthnot <- arbuthnot %>% 
  mutate(total = boys + girls)

Ahora vemos los nombreas de las variables nuevamente para verificar que existe una nueva columna y es el total

names(arbuthnot)
## [1] "year"  "boys"  "girls" "total"

Ahora graficamos el número total de niños bautizados por año pero con línea

ggplot(data = arbuthnot, aes(x = year, y = total))+
  geom_line()

Ahora le añadimos los puntos a la línea

ggplot(data = arbuthnot, aes(x = year, y = total))+
  geom_line()+
  geom_point()

Ahora generamos una gráfica con el número de niños bautizados por año

ggplot(data = arbuthnot, aes(x = year, y = boys))+
  geom_line() + 
  geom_point()

Podemos comparar si la cantidad de niños fue mayor que las niñas, y nos regresa un argumento booleano, ya sea TRUE o FALSE si se cumple el argumento, con la siguiente expresión

arbuthnot <- arbuthnot %>% 
  mutate(more_boys = boys > girls)

Verificamos que se añadió la columna aduecatamente

arbuthnot$more_boys
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [31] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [46] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [61] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [76] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

En todos los casos se cumple que hubo más niñps bautizados comparado con las niñas.

Realizamos nuevos análisis con una nueva base de datos, que incliye los registros de nacimientos de los Estados Unidos.

data(present)

Verificamos el inicio de los datos con el comando head

head(present)
## # A tibble: 6 × 3
##    year    boys   girls
##   <dbl>   <dbl>   <dbl>
## 1  1940 1211684 1148715
## 2  1941 1289734 1223693
## 3  1942 1444365 1364631
## 4  1943 1508959 1427901
## 5  1944 1435301 1359499
## 6  1945 1404587 1330869

¿Cuántas bariables incluye el dataset? La respuesta es 3. Lo observamos con el comando names

names(present)
## [1] "year"  "boys"  "girls"

¿Cuántos años incluye el dataset? Lo podemos ver con la función range, que regresa el mínimo y el máximo

range(present$year)
## [1] 1940 2013

Calculamos el número de años haciendo la operación. 73 años

2013 - 1940
## [1] 73

Calculamos el número total de nacimientos y los almacenamos en una nuvea variable llamada total.

present <- present %>% 
  mutate(total = boys + girls)

Luego calculamos al proporción de niños por cada años y lo guardamos en una nueva variable llamada prop_boys.

present <- present %>% 
  mutate(prop_boys = boys/total)

Graficamos la proporción de niños por año

ggplot(data = present, aes(x = year, y = prop_boys)) + 
  geom_line()+
  geom_point()

¿La proporción de niños nacidos en US ha disminuido conforme pasa el tiempo? La respuesta es si

Ahora creamos una nuvea variable llamada more_boys que contiene el valor TRUE si en ese año hubo más niños que niñas, o FALSE si no lo fue. Con base en esa variable, ¿Cuál de los siguientes afirmaciones es cierta?

  1. Cada año hubo más niñas que niños
  2. Cada año hubo más niños que niñas
  3. La mitad de los años hubo más niños, y la otra mitad hubo más niñas
present <- present %>% 
  mutate(more_boys = boys > girls)

Ahora vemos todos los valores de esa variable

present$more_boys
##  [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [31] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [46] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [61] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

Efectivamente, todos los años hubo más niños que niñas. Por lo que la respuesta a la pregunta anterior es la letra b.

Ahora calculamos la proporción niños-niñas y la guardamos en una nueva variable llamada prop_boy_girl.

present <- present %>% 
  mutate(prop_boy_girl = boys / girls)

Graficamos la proporción en función del tiempo

ggplot(data = present, aes(x = year, y = prop_boy_girl)) + 
  geom_line()+
  geom_point()

Which of the following best describes the trend?

  1. There appears to be no trend in the boy-to-girl ratio from 1940 to 2013.
  2. There is initially an increase in boy-to-girl ratio, which peaks around 1960. After 1960 there is a decrease in the boy-to-girl ratio, but the number begins to increase in the mid 1970s.
  3. There is initially a decrease in the boy-to-girl ratio, and then an increase between 1960 and 1970, followed by a decrease.
  4. The boy-to-girl ratio has increased over time.
  5. There is an initial decrease in the boy-to-girl ratio born but this number appears to level around 1960 and remain constant since then.

Considero que la respuesta correcta es la letra c

¿En qué año se vio el mayor número de nacimientos en U.S.?

present %>% 
  arrange(desc(total))
## # A tibble: 74 × 7
##     year    boys   girls   total prop_boys more_boys prop_boy_girl
##    <dbl>   <dbl>   <dbl>   <dbl>     <dbl> <lgl>             <dbl>
##  1  2007 2208071 2108162 4316233     0.512 TRUE               1.05
##  2  1961 2186274 2082052 4268326     0.512 TRUE               1.05
##  3  2006 2184237 2081318 4265555     0.512 TRUE               1.05
##  4  1960 2179708 2078142 4257850     0.512 TRUE               1.05
##  5  1957 2179960 2074824 4254784     0.512 TRUE               1.05
##  6  2008 2173625 2074069 4247694     0.512 TRUE               1.05
##  7  1959 2173638 2071158 4244796     0.512 TRUE               1.05
##  8  1958 2152546 2051266 4203812     0.512 TRUE               1.05
##  9  1962 2132466 2034896 4167362     0.512 TRUE               1.05
## 10  1956 2133588 2029502 4163090     0.513 TRUE               1.05
## # ℹ 64 more rows

El año 2007 fue el año con mayor número de nacimientos