Preguntas para comenzar

DEMOSLE CLICK A ESTE LINK PARA COMENZAR

library(dplyr)     # 
library(ggplot2)   #
library(gganimate) #
library(gapminder) #
library(ggthemes)  #
library(plotly)    #
head(gapminder)

Primera Parte: Inspección de la Base de datos

head(gapminder)
dim(gapminder)
## [1] 1704    6
str(gapminder)
## tibble[,6] [1,704 × 6] (S3: tbl_df/tbl/data.frame)
##  $ country  : Factor w/ 142 levels "Afghanistan",..: 1 1 1 1 1 1 1 1 1 1 ...
##  $ continent: Factor w/ 5 levels "Africa","Americas",..: 3 3 3 3 3 3 3 3 3 3 ...
##  $ year     : int [1:1704] 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 ...
##  $ lifeExp  : num [1:1704] 28.8 30.3 32 34 36.1 ...
##  $ pop      : int [1:1704] 8425333 9240934 10267083 11537966 13079460 14880372 12881816 13867957 16317921 22227415 ...
##  $ gdpPercap: num [1:1704] 779 821 853 836 740 ...

Análisis Gráfico exploratorio

Histograma

ggplot(data = gapminder, aes(x = lifeExp))

ggplot(data = gapminder, aes(x = lifeExp)) +   
  geom_histogram()
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Tarea: Hacer el histograma del gdpPercap per capita en vez de la esperanza de vida. (#gdpPercap)

Calculemos la experanza de vida promedio por continente

gapminder %>% group_by(continent) %>%  summarise(promedio=mean(lifeExp))

Ahora, haremos un gráfico sobre la tabla que construimos en el paso anterior

gapminder %>% group_by(continent) %>%  summarise(promedio=mean(lifeExp)) %>% ggplot(aes(x=continent, y=promedio)) + geom_bar(stat='identity')

Ahora le vamos agregar título y fondo blanco

gapminder %>% group_by(continent) %>%  summarise(promedio=mean(lifeExp)) %>% ggplot(aes(x=continent, y=promedio)) + geom_bar(stat='identity') + ggtitle("Esperanza de vida por Continente" ) + theme_bw()

¿Qué tal si trabajaramos en the Economomist?

gapminder %>% group_by(continent) %>%  summarise(promedio=mean(lifeExp)) %>% ggplot(aes(x=continent, y=promedio)) + geom_bar(stat='identity') + ggtitle("Esperanza de vida por Continente" ) + 
theme_economist() + scale_colour_economist() 

Probemos un recurso muy importante, agreguemos colores para hacer más fácil de entender el gráfico.

gapminder %>% group_by(continent) %>%  summarise(promedio=mean(lifeExp)) %>% ggplot(aes(x=continent, y=promedio, fill=continent)) + geom_bar(stat='identity') + ggtitle("Esperanza de vida por Continente" )  + theme_clean()

Probemos con el siguiente codigo: ``jCountries <- c(“Canada”, “Rwanda”, “Cambodia”, “Mexico”)

ggplot(subset(gapminder, country %in% jCountries),

aes(x = year, y = lifeExp, color = country)) + geom_line() + geom_point()``

Podemos hacerlo con dplyr en un solo paso?

Tarea: Hacer un gráfico de líneas

gapminder %>%  filter(country, ("Canada", "Rwanda", "Cambodia", "Mexico"))  %>% 
## Error: <text>:1:41: unexpected ','
## 1: gapminder %>%  filter(country, ("Canada",
##                                             ^

¿Cuál es la diferencia entre == y %in%?

%in% busca coincidencia de valores.

== es un operador lógico destinado a comparar si dos cosas son exactamente iguales.

Pongo las definiciones en inglés porque considero que es más claro

%in% is value matching and “returns a vector of the positions of (first) matches of its first argument in its second” (See help(‘%in%’)) This means you could compare vectors of different lengths to see if elements of one vector match at least one element in another. The length of output will be equal to the length of the vector being compared (the first one).

== is logical operator meant to compare if two things are exactly equal. If the vectors are of equal length, elements will be compared element-wise. If not, vectors will be recycled. The length of output will be equal to the length of the longer vector.

Podemos hacer tambien un gráfico de puntos, pero solo del año 2007

gapminder %>%  filter(year==2007) %>%  ggplot(aes(x=gdpPercap, y=lifeExp)) +
  geom_point()

gapminder %>%  filter(year==2007) %>%  ggplot(aes(x=gdpPercap, y=lifeExp)) +
  geom_point(aes(size=pop))

gapminder %>%  filter(year==2007) %>%  ggplot(aes(x=gdpPercap, y=lifeExp)) +
  geom_point(aes(size=pop, color=continent))

gapminder %>%  filter(year==2007) %>%  ggplot(aes(x=gdpPercap, y=lifeExp)) +
  geom_point(aes(size=pop, color=continent)) + 
  ggtitle('Relación entre esperanza de vida y GDP per capita') +
  xlab('GDP per capita ($/año)') +
  ylab('Esperanza de vida (años)')

UNA SOPRESA ANTES DE IR A LA SEGUNDA PARTE

ggplotly(gapminder %>%  filter(year==2007) %>%  ggplot(aes(x=gdpPercap, y=lifeExp)) +
  geom_point(aes(size=pop, color=country)) + 
  ggtitle('Relación entre esperanza de vida y GDP per capita') +
  xlab('GDP per capita ($/año)') +
  ylab('Esperanza de vida (años)'))
ggplot(
  gapminder, 
  aes(x = gdpPercap, y=lifeExp, size = pop, colour = country)
  ) +
  geom_point(show.legend = FALSE, alpha = 0.7) +
  scale_color_viridis_d() +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  labs(x = "GDP per capita", y = "Life expectancy")