group_by: cambiar el dominio de acción de los verbos
¿Qué pasa si queremos el promedio de lifeExp pero ahora por continente? ¿o filtrar observaciones que cumplan cierta condici+ón lógica pero para cada uno de los distintos años (year) de nuestra data gapminder?
group_by actuará cambiando el dominio en que se ejecuta cada verbos.Necesitamos agrupar (group_by) por continente (continent) para ejecutar el verbo summarise y crear la variable expectativa de vida promedio (avgLifeExp)
#cambiamos el dominio de jecución (o análisis de los verbos)
por_continente <- group_by(gapminder, continent)
#en vez de aplicar los verbhos sobre gapminder, lo hacemos sobre
#por_continente
summarise(por_continente, avgLifeExp = mean(lifeExp))
tabla por bloques (composición con los verbos)
ggplot(data =
mutate(
select(
filter(
gapminder,
country == "Chile"),
year,
pop,
gdpPercap
),
gdpMillion = (gdpPercap * pop) / 1e6
)
) +
geom_line(mapping = aes(x = year, y = gdpMillion))
Resumen de la composición (asignar variables a los verbos)
chile <- filter(gapminder, country == "Chile")
chile2 <- select(chile, year, pop, gdpPercap)
chile3 <- mutate(chile2, gdpMillion = (gdpPercap * pop) / 1e6)
ggplot(data = chile3) +
geom_line(mapping = aes(x = year, y = gdpMillion))
^ Esta operación determina en el recuadro de Data las nuevas variables (chile, chile2, chile3)
Primero, cargar paquetes necesarios para el documento:
library(ggplot2)
library(dplyr)
#paquete de data:
library(titanic)
Exploramos la data de titanic
df <- dplyr::bind_rows(titanic::titanic_train,
titanic::titanic_test)
glimpse(df)
Observations: 1,309
Variables: 12
$ PassengerId <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 2...
$ Survived <int> 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, ...
$ Pclass <int> 3, 1, 3, 1, 3, 3, 1, 3, 3, 2, 3, 1, 3, 3, 3, 2, 3, 2, 3, 3, 2, 2, 3, 1, ...
$ Name <chr> "Braund, Mr. Owen Harris", "Cumings, Mrs. John Bradley (Florence Briggs ...
$ Sex <chr> "male", "female", "female", "female", "male", "male", "male", "male", "f...
$ Age <dbl> 22, 38, 26, 35, 35, NA, 54, 2, 27, 14, 4, 58, 20, 39, 14, 55, 2, NA, 31,...
$ SibSp <int> 1, 1, 0, 1, 0, 0, 0, 3, 0, 1, 1, 0, 0, 1, 0, 0, 4, 0, 1, 0, 0, 0, 0, 0, ...
$ Parch <int> 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 0, 0, 5, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, ...
$ Ticket <chr> "A/5 21171", "PC 17599", "STON/O2. 3101282", "113803", "373450", "330877...
$ Fare <dbl> 7.2500, 71.2833, 7.9250, 53.1000, 8.0500, 8.4583, 51.8625, 21.0750, 11.1...
$ Cabin <chr> "", "C85", "", "C123", "", "", "E46", "", "", "", "G6", "C103", "", "", ...
$ Embarked <chr> "S", "C", "S", "S", "S", "Q", "S", "S", "S", "C", "S", "S", "S", "S", "S...
En variable categórica: geom_bar Distribución de pasajeros por sexo que hay en los datos.
ggplot(data = df) +
geom_bar(mapping = aes(x = Sex), fill = "pink", colour = "orange") +
theme_bw() +
ggtitle("Para observar la variación de una variable categórica: geom_bar")
Calcular observaciones
count(df, Sex)
#crtl+ shift + M = operador %>%
df %>%
select(Fare)
Fijar estos valores en un eje (pendiente)
ggplot(data = df)
#head nos arroja las primeras 6 observaciones de la tabla que nos entrega count (df, Fare)
head(count(df, Fare))
df %>%
count(Fare) %>%
ggplot() +
geom_point(mapping = aes(x = Fare, y = 0, size = n),
alpha = 1 / 5,
shape = 21,
fill = "red",
colour = "black") +
theme_bw()
Definición de intervalos de tarifas
#Crear intervalos y clasificar a cual de estos pertenece los valores de una variable continua.
df %>%
select(Fare) %>%
mutate(intervalos = cut_width(Fare, 10))
Histograma = gráfico de barras para variables continuas (histogram)
ggplot(data = df) +
geom_histogram(mapping = aes(x = Fare), binwidth = 10, fill = "orange", colour = "black") +
theme_bw() +
ggtitle("Para observar la variación de una variable continua: geom_histogram")
Inspeccionar covariacion entre variables Entre variable categórica y continua: geom_freqpoly
ggplot(data = df) +
geom_histogram(mapping = aes(x = Fare, fill = Sex), colour = "black") +
facet_wrap(~ Sex) +
theme_bw()
ggplot(data = df) +
geom_freqpoly(mapping = aes(x = Fare, colour = factor(Pclass)),
binwidth = 10,
size = 0.8) +
theme_bw() +
ggtitle("Para compara distintas distribuciones: geom_freqpoly.")
Tarea prox. semana Explicar gráficos: comparar según variables empleadas en el gráfico Modo de “reportaje” (informar qué pasó)