Skip to content

Instantly share code, notes, and snippets.

@jrosell
Last active June 1, 2022 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrosell/10e5ca8b0676feda47438bebf9e5f1b6 to your computer and use it in GitHub Desktop.
Save jrosell/10e5ca8b0676feda47438bebf9e5f1b6 to your computer and use it in GitHub Desktop.
Ordenar datos tabulares (alargar filas, ensanchar columnas, valores faltantes, unir, separar)
if(!require(tidyverse)) install.packages("tidyverse")
library(tidyverse)
# Alargar filas del data.frame reuniendo/fundiendo las columnas en nueva filas.
relig_income
longer <- relig_income %>% pivot_longer(-religion, names_to = "income", values_to = "count") %>% print()
# Ensanchar columnas del data.frame esparciendo/proyectando las filas en nuevas columnas.
us_rent_income
wider <- us_rent_income %>% pivot_wider(names_from = variable, values_from = c(estimate, moe)) %>% print()
# Hacer explícita la ausencia de valores faltantes implícitos
revenue <- tibble(
year = c(rep(2019, 12), rep(2020, 3)),
month = c(1:12, 1:2, 6),
eur = c("4.420,2€", "3.502,3€","4.701,4€", "3.602,3€", "4.420,2€", "3.502,3€","4.701,4€", "3.602,3€", "4.420,2€", "3.502,3€","4.701,4€", "3.602,3€", "3.502,3€","NA", "3.602,3€")
)
revenue2 <- revenue %>% complete(year, month) %>% filter(!(year == 2020 & month > 6)) %>% print(n = Inf)
# Unir variables multicolumna
options(pillar.sigfig = 7)
revenue2 %>%
unite(date, year, month, sep = "-") %>%
mutate(
date = parse_date(date, format = "%Y-%m"),
eur = parse_number(eur, locale = locale(decimal_mark = ",", grouping_mark = "."))
) %>% print()
# Separar columnas multivariables
ciudades <- tribble(
~ciudad, ~pob, ~latlang,
"Madrid", 3167000, "40.420,-3.710",
"Barcelona", 1549400, "41.400,2.170"
)
ciudades %>% separate(latlang, into = c("latitude", "longitude"), sep = ",", convert = TRUE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment