Módulo práctico de ITA
(Grupo M)
Aprendimos a cargar datos y a hacerlos TIDY. También vimos la “teoría” del tidyverse. Ahora nos centraremos en usar el tidyverse para transformar nuestros datos, para obtener resultados. Para ello usaremos ejemplos
vimos ya la “teoría” del tidyverse
dplyr es el paquete más importante a la hora de manipular datos.select(), filter(), mutate(), arrange(), rename(), summarise() y group_by().%>%)para aprender a manipular datos con dplyr (y obtener resultados)
Es importante saber cómo contar las observaciones que tenemos en distintos grupos
Por ejemplo, contar cuántas mujeres hay, o cuántas observaciones hay en cada continente, o cuántas empresas en diferentes sectores, …
… vamos a CONTAR
tenemos 2 formas distintas de contar el nº de observaciones (o filas)
1. Usando summarise() con n()
… seguimos CONTANDO
Pero ahora contamos el nº de observaciones de distintos grupos (por ejemplo el nº de observaciones de cada continente)
… aún seguimos CONTANDO
Contamos el nº de observaciones de distintos grupos, pero ahora definidos por dos variables (por ejemplo el nº de observaciones de cada continente y año)
… ver/obtener observaciones DISTINTAS con distinct()
… CONTAR observaciones DISTINTAS con n_distinct()
calculando ESTADÍSTICOS: máximo, mínimo, media, ……
calcular ESTADÍSTICOS (máximo, mínimo y media) por continente
ESTADÍSTICOS para Europa año a año ……
#- calcular estadísticos por CONTINENTE Y AÑO
aa <- gapminder %>%
1 group_by(continent, year) %>%
2 summarise(maximo = max(lifeExp, na.rm = TRUE),
minimo = min(lifeExp, na.rm = TRUE),
mean = mean(lifeExp, na.rm = TRUE) ) %>%
3 ungroup() %>%
4 filter(continent == "Europe")group_by() es una buena práctica hacer después un ungroup()
| continent | year | maximo | minimo | mean |
|---|---|---|---|---|
| Europe | 1952 | 72.67 | 43.59 | 64.41 |
| Europe | 1957 | 73.47 | 48.08 | 66.70 |
| Europe | 1962 | 73.68 | 52.10 | 68.54 |
| Europe | 1967 | 74.16 | 54.34 | 69.74 |
| Europe | 1972 | 74.72 | 57.01 | 70.78 |
| Europe | 1977 | 76.11 | 59.51 | 71.94 |
| Europe | 1982 | 76.99 | 61.04 | 72.81 |
| Europe | 1987 | 77.41 | 63.11 | 73.64 |
| Europe | 1992 | 78.77 | 66.15 | 74.44 |
| Europe | 1997 | 79.39 | 68.83 | 75.51 |
| Europe | 2002 | 80.62 | 70.84 | 76.70 |
| Europe | 2007 | 81.76 | 71.78 | 77.65 |
en la slide anterior, al calcular la esperanza de vida media por continente,
estábamos promediando países con diferente población 🫣
Vuelve a calcular la esperanza de vida media por continente y año, PERO ahora, ten en cuenta que los países tienen distinto nº de habitantes
Es decir, hemos de calcular la media, pero ponderada por la población (pop)
Pista: Igual puedes reusar el código de la página anterior, pero en lugar de usar mean() usar weighted.mean()
Tendrás que mirar la ayuda de weighted.mean() para usar un nuevo argumento
aa <- gapminder %>%
group_by(continent, year) %>%
1 summarise(mean = mean(lifeExp, na.rm = TRUE),
mean_w = weighted.mean(lifeExp, w = pop, na.rm = TRUE)) %>%
ungroup() %>%
2 filter(year == 2007)calculando CRECIMIENTOS
aa <- gapminder %>%
1 select(country, year, lifeExp) %>%
2 group_by(country) %>%
3 arrange(year) %>%
4 mutate(crecimiento = lifeExp - lag(lifeExp)) %>%
5 ungroup() %>%
6 filter(country == "Spain")group_by() es una buena práctica hacer después un ungroup()
| country | year | lifeExp | crecimiento |
|---|---|---|---|
| Spain | 1952 | 64.94 | NA |
| Spain | 1957 | 66.66 | 1.72 |
| Spain | 1962 | 69.69 | 3.03 |
| Spain | 1967 | 71.44 | 1.75 |
| Spain | 1972 | 73.06 | 1.62 |
| Spain | 1977 | 74.39 | 1.33 |
| Spain | 1982 | 76.30 | 1.91 |
| Spain | 1987 | 76.90 | 0.60 |
| Spain | 1992 | 77.57 | 0.67 |
| Spain | 1997 | 78.77 | 1.20 |
| Spain | 2002 | 79.78 | 1.01 |
| Spain | 2007 | 80.94 | 1.16 |
calculando CRECIMIENTOS ACUMULADOS
aa <- gapminder %>%
select(country, year, lifeExp) %>%
1 group_by(country) %>%
2 arrange(year) %>%
3 mutate(crec = lifeExp - lag(lifeExp)) %>%
4 mutate(crec_acu = lifeExp - first(lifeExp)) %>%
5 ungroup() %>%
filter(country == "Spain") group_by() es una buena práctica hacer después un ungroup()
| country | year | lifeExp | crec | crec_acu |
|---|---|---|---|---|
| Spain | 1952 | 64.94 | NA | 0.00 |
| Spain | 1957 | 66.66 | 1.72 | 1.72 |
| Spain | 1962 | 69.69 | 3.03 | 4.75 |
| Spain | 1967 | 71.44 | 1.75 | 6.50 |
| Spain | 1972 | 73.06 | 1.62 | 8.12 |
| Spain | 1977 | 74.39 | 1.33 | 9.45 |
| Spain | 1982 | 76.30 | 1.91 | 11.36 |
| Spain | 1987 | 76.90 | 0.60 | 11.96 |
| Spain | 1992 | 77.57 | 0.67 | 12.63 |
| Spain | 1997 | 78.77 | 1.20 | 13.83 |
| Spain | 2002 | 79.78 | 1.01 | 14.84 |
| Spain | 2007 | 80.94 | 1.16 | 16.00 |
Una vez hemos contado, muchas veces interesa saber el porcentaje que representa cada grupo respecto al total
Para calcular esos porcentajes, hay que dividir el nº de observaciones de cada grupo por el total. Veamos cómo hacerlo
calculando PORCENTAJES (a mano)
Por ejemplo, si en una muestra de 100 personas hay 70 personas con el pelo moreno, los morenos son el 70% del total
Evidentemente, se calcula dividiendo: 70/100 = 0.7; si lo multiplicamos x100, un 70%
un ejemplo
calculando PORCENTAJES (con R à la tidyverse)
#- Calcular % de población de cada continente
aa <- gapminder %>%
1 group_by(continent, year) %>%
2 summarise(pob_continent = sum(pop, na.rm = TRUE)) %>% ungroup() %>%
3 group_by(year) %>%
4 mutate(pob_mundo = sum(pob_continent),
5 pob_percent = pob_continent/pob_mundo * 100) %>%
ungroup()1bb <- aa %>% filter(year %in% c(1952, 2007))| continent | year | pob_continent | pob_mundo | pob_percent |
|---|---|---|---|---|
| Africa | 1952 | 237640501 | 2406957150 | 9.87 |
| Africa | 2007 | 929539692 | 6251013179 | 14.87 |
| Americas | 1952 | 345152446 | 2406957150 | 14.34 |
| Americas | 2007 | 898871184 | 6251013179 | 14.38 |
| Asia | 1952 | 1395357351 | 2406957150 | 57.97 |
| Asia | 2007 | 3811953827 | 6251013179 | 60.98 |
| Europe | 1952 | 418120846 | 2406957150 | 17.37 |
| Europe | 2007 | 586098529 | 6251013179 | 9.38 |
| Oceania | 1952 | 10686006 | 2406957150 | 0.44 |
| Oceania | 2007 | 24549947 | 6251013179 | 0.39 |
Extensión: tabla con la importancia (en términos de población) de cada continente en el tiempo
- Antes hemos calculado (en aa) el % que representa la población de cada continente a lo largo del tiempo, pero lo tenemos en formato largo
| continent | year | pob_continent | pob_mundo | pob_percent |
|---|---|---|---|---|
| Africa | 1952 | 237640501 | 2406957150 | 9.87 |
| Africa | 1957 | 264837738 | 2664404580 | 9.94 |
| Americas | 1952 | 345152446 | 2406957150 | 14.34 |
Los datos de aa no son presentables en una tabla porque tiene 60 filas!!!!
Ahora quiero hacer la tabla presentable: he de pasarla a formato ancho
| year | pob_mundo | Africa | Americas | Asia | Europe | Oceania |
|---|---|---|---|---|---|---|
| 1952 | 2.406.957.150 | 9.9 | 14.3 | 58.0 | 17.4 | 0.4 |
| 1957 | 2.664.404.580 | 9.9 | 14.5 | 58.7 | 16.4 | 0.4 |
| 1962 | 2.899.782.974 | 10.2 | 14.9 | 58.5 | 15.9 | 0.5 |
| 1967 | 3.217.478.384 | 10.4 | 14.9 | 59.2 | 15.0 | 0.5 |
| 1972 | 3.576.977.158 | 10.6 | 14.8 | 60.1 | 14.0 | 0.5 |
| 1977 | 3.930.045.807 | 11.0 | 14.7 | 60.7 | 13.2 | 0.4 |
| 1982 | 4.289.436.840 | 11.6 | 14.7 | 60.9 | 12.4 | 0.4 |
| 1987 | 4.691.477.418 | 12.3 | 14.6 | 61.2 | 11.6 | 0.4 |
| 1992 | 5.110.710.260 | 12.9 | 14.5 | 61.3 | 10.9 | 0.4 |
| 1997 | 5.515.204.472 | 13.5 | 14.4 | 61.3 | 10.3 | 0.4 |
| 2002 | 5.886.977.579 | 14.2 | 14.4 | 61.2 | 9.8 | 0.4 |
| 2007 | 6.251.013.179 | 14.9 | 14.4 | 61.0 | 9.4 | 0.4 |
calculando RANKINGs
aa <- gapminder %>%
1 select(country, year, lifeExp) %>%
2 group_by(year) %>%
3 mutate(rank_1 = row_number(desc(lifeExp))) %>%
mutate(rank_2 = min_rank(desc(lifeExp)) ) %>%
ungroup() | country | year | lifeExp | rank_1 | rank_2 |
|---|---|---|---|---|
| Spain | 1952 | 65 | 24 | 24 |
| Spain | 1957 | 67 | 26 | 26 |
| Spain | 1962 | 70 | 18 | 18 |
| Spain | 1967 | 71 | 10 | 10 |
| Spain | 1972 | 73 | 8 | 8 |
| Spain | 1977 | 74 | 8 | 8 |
| Spain | 1982 | 76 | 4 | 4 |
| Spain | 1987 | 77 | 5 | 5 |
| Spain | 1992 | 78 | 7 | 7 |
| Spain | 1997 | 79 | 8 | 8 |
| Spain | 2002 | 80 | 8 | 8 |
| Spain | 2007 | 81 | 6 | 6 |
ifelse() y case_when()ifelse(): ejecuta “algo” de manera condicional
case_when(): es una generalización de ifelse()
ifelse(): ejecuta “algo” de manera condicional
veamos algunos ejemplos
aa <- gapminder %>%
select(-pop) %>%
mutate(X1 = ifelse(lifeExp > 70, "longevo", "no longevo")) %>%
mutate(X2 = ifelse(gdpPercap > 10000, "rico", "pobre")) %>%
mutate(X3 = ifelse(lifeExp > 70 & gdpPercap > 10000,
"longevo y rico",
"no longevo y/o pobre")) %>%
mutate(X4 = ifelse(continent == "Europe", "europeo", "no europeo")) el resultado es:
aa %>% filter(country %in% c("Spain", "Angola")) %>%
filter(year %in% c(1952, 2007)) %>%
gt::gt() %>%
gt::opt_stylize(style = 3) %>%
gt::cols_align(align = "center")| country | continent | year | lifeExp | gdpPercap | X1 | X2 | X3 | X4 |
|---|---|---|---|---|---|---|---|---|
| Angola | Africa | 1952 | 30.015 | 3520.610 | no longevo | pobre | no longevo y/o pobre | no europeo |
| Angola | Africa | 2007 | 42.731 | 4797.231 | no longevo | pobre | no longevo y/o pobre | no europeo |
| Spain | Europe | 1952 | 64.940 | 3834.035 | no longevo | pobre | no longevo y/o pobre | europeo |
| Spain | Europe | 2007 | 80.941 | 28821.064 | longevo | rico | longevo y rico | europeo |
case_when(): es una generalización de ifelse()
A ver si entiendes este ejemplo:
aa <- gapminder %>%
group_by(continent, year) %>%
mutate(media_lifeExp = mean(lifeExp)) %>%
mutate(media_gdpPercap = mean(gdpPercap)) %>%
mutate(GOOD_or_BAD = case_when(
lifeExp > mean(lifeExp) & gdpPercap > mean(gdpPercap) ~ "good",
lifeExp < mean(lifeExp) & gdpPercap < mean(gdpPercap) ~ "bad" ,
lifeExp < mean(lifeExp) | gdpPercap < mean(gdpPercap) ~ "medium",
.default = "otros casos" ) )| country | continent | year | lifeExp | gdpPercap | media_lifeExp | media_gdpPercap | GOOD_or_BAD |
|---|---|---|---|---|---|---|---|
| Spain | Europe | 1952 | 64,94 | 3.834,03 | 64,41 | 5.661,06 | medium |
| Spain | Europe | 1957 | 66,66 | 4.564,80 | 66,70 | 6.963,01 | bad |
| Spain | Europe | 1962 | 69,69 | 5.693,84 | 68,54 | 8.365,49 | medium |
| Spain | Europe | 1967 | 71,44 | 7.993,51 | 69,74 | 10.143,82 | medium |
| Spain | Europe | 1972 | 73,06 | 10.638,75 | 70,78 | 12.479,58 | medium |
| Spain | Europe | 1977 | 74,39 | 13.236,92 | 71,94 | 14.283,98 | medium |
| Spain | Europe | 1982 | 76,30 | 13.926,17 | 72,81 | 15.617,90 | medium |
| Spain | Europe | 1987 | 76,90 | 15.764,98 | 73,64 | 17.214,31 | medium |
| Spain | Europe | 1992 | 77,57 | 18.603,06 | 74,44 | 17.061,57 | good |
| Spain | Europe | 1997 | 78,77 | 20.445,30 | 75,51 | 19.076,78 | good |
| Spain | Europe | 2002 | 79,78 | 24.835,47 | 76,70 | 21.711,73 | good |
| Spain | Europe | 2007 | 80,94 | 28.821,06 | 77,65 | 25.054,48 | good |
dplyrResumen: qué hemos aprendido a calcular
Contar observaciones: n() y count()
Ver y contar observaciones distintas: distinct() y n_distinct()
Calcular estadísticos: summarise() con max(), min(), mean() o weighted.mean()
Calcular crecimientos: lag() y first()
Calcular porcentajes: dividir el valor de cada grupo por el total
Calcular rankings: row_number() y min_rank()
Crear variables según una condición: ifelse() y case_when()
casi siempre con la misma receta: group_by() + summarise() o mutate()