Objetivo: Aprender importar, transformar e visualizar dados no R com o tidyverse, usando pouquíssimas bases (principalmente
penguins) e um exemplo prático para cada conceito.
Uma observação por linha; uma variável por coluna; um valor por célula.
Verbos coesos (select, filter, mutate, summarise, …).
Pipelines para legibilidade (|> recomendado).
Exemplo (estruturar e encadear):
penguins |>
select(species, bill_length_mm, body_mass_g) |>
filter(!is.na(bill_length_mm), !is.na(body_mass_g)) |>
mutate(relacao = body_mass_g / bill_length_mm) |>
head(3)
select: dropped 5 variables (island, bill_depth_mm, flipper_length_mm, sex, year)
filter: removed 2 rows (1%), 342 rows remaining
mutate: new variable 'relacao' (double) with 334 unique values and 0% NA
|> (preferido) e
magrittr %>% (legado).```r
1:5 |> mean()
```
```
[1] 3
```
Conceitos: tibble,
glimpse, impressão amigável, tipos.
Exemplo: criar tibble e inspecionar
glimpse(tb)
Rows: 5
Columns: 3
$ id <int> 1, 2, 3, 4, 5
$ nome <chr> "ana", "bruno", "carla", "diego", "eva"
$ nota <dbl> 7.5, 8.2, 6.9, 9.1, 7.8
glimpse(penguins)
Rows: 344
Columns: 8
$ species <fct> Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adelie, Adel…
$ island <fct> Torgersen, Torgersen, Torgersen, Torgersen, Torgersen, Torgersen, Torgersen, Torgersen, Torgersen, Torgersen, Torger…
$ bill_length_mm <dbl> 39.1, 39.5, 40.3, NA, 36.7, 39.3, 38.9, 39.2, 34.1, 42.0, 37.8, 37.8, 41.1, 38.6, 34.6, 36.6, 38.7, 42.5, 34.4, 46.0…
$ bill_depth_mm <dbl> 18.7, 17.4, 18.0, NA, 19.3, 20.6, 17.8, 19.6, 18.1, 20.2, 17.1, 17.3, 17.6, 21.2, 21.1, 17.8, 19.0, 20.7, 18.4, 21.5…
$ flipper_length_mm <int> 181, 186, 195, NA, 193, 190, 181, 195, 193, 190, 186, 180, 182, 191, 198, 185, 195, 197, 184, 194, 174, 180, 189, 18…
$ body_mass_g <int> 3750, 3800, 3250, NA, 3450, 3650, 3625, 4675, 3475, 4250, 3300, 3700, 3200, 3800, 4400, 3700, 3450, 4500, 3325, 4200…
$ sex <fct> male, female, female, NA, female, male, female, male, NA, NA, NA, NA, female, male, male, female, female, male, fema…
$ year <int> 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 2007, 20…
Exemplo: limpar nomes de colunas
tb_sujos <- tibble("Nome do Aluno" = c("Ana","Bruno"), "Nota Final (%)" = c(8.7, 9.2))
tb_limpos <- tb_sujos |> janitor::clean_names()
tb_limpos
NA
readrConceitos: read_csv,
write_csv, tipos e NA.
Exemplo: escrever e ler CSV
tmp <- tempfile(fileext = ".csv")
write_csv(tb, tmp)
dados <- readr::read_csv(tmp, show_col_types = FALSE)
glimpse(dados)
Rows: 5
Columns: 3
$ id <dbl> 1, 2, 3, 4, 5
$ nome <chr> "ana", "bruno", "carla", "diego", "eva"
$ nota <dbl> 7.5, 8.2, 6.9, 9.1, 7.8
Exemplo: declarar tipos e NA
glimpse(dados2)
Rows: 2
Columns: 3
$ id <int> 1, 2
$ nome <chr> "Ana", "Bruno"
$ nota <dbl> 8.1, NA
dplyrselect e helpersExemplo: escolher colunas e renomear
penguins |>
select(especie = species, starts_with("bill"))
select: renamed one variable (especie) and dropped 5 variables
arrangeExemplo: ordenar por massa decrescente
penguins |>
arrange(desc(body_mass_g)) |>
#arrange(body_mass_g) |>
select(species, body_mass_g) |>
head(5)
select: dropped 6 variables (island, bill_length_mm, bill_depth_mm, flipper_length_mm, sex, …)
Exemplo: filtrar linhas com condições lógicas
penguins |>
filter(species == "Adelie", !is.na(flipper_length_mm))
filter: removed 193 rows (56%), 151 rows remaining
dplyrselect e helpersExemplo: escolher colunas e renomear
penguins |> select(especie = species, starts_with("bill"))
select: renamed one variable (especie) and dropped 5 variables
arrangeExemplo: ordenar por massa decrescente
penguins |> arrange(desc(body_mass_g)) |> select(species, body_mass_g) |> head(5)
select: dropped 6 variables (island, bill_length_mm, bill_depth_mm, flipper_length_mm, sex, …)
filterExemplo: filtrar linhas com condições lógicas
penguins |> filter(species == "Adelie", !is.na(flipper_length_mm))
filter: removed 193 rows (56%), 151 rows remaining
mutate, case_when e acrossExemplo: criar variável categórica por faixas
penguins |>
mutate(faixa_massa = case_when(
body_mass_g < 3500 ~ "leve",
body_mass_g < 4500 ~ "média",
TRUE ~ "pesada" )) |> count(faixa_massa)
mutate: new variable 'faixa_massa' (character) with 3 unique values and 0% NA
count: now 3 rows and 2 columns, ungrouped
Exemplo: padronizar múltiplas colunas numéricas
(across)
penguins |>
mutate(across(c(bill_length_mm, bill_depth_mm), ~ (.x - mean(.x, na.rm = TRUE))/sd(.x, na.rm = TRUE)))
mutate: changed 342 values (99%) of 'bill_length_mm' (0 new NAs)
changed 342 values (99%) of 'bill_depth_mm' (0 new NAs)
summarise, group_by, n()Exemplo: resumo por espécie e sexo
penguins |> group_by(species, sex) |>
summarise(n = n(),
massa_media = mean(body_mass_g, na.rm = TRUE),
asa_media = mean(flipper_length_mm, na.rm = TRUE),
.groups = "drop" )
group_by: 2 grouping variables (species, sex)
summarise: now 8 rows and 5 columns, ungrouped
Exemplo com pequenas tabelas sintéticas (sem sair do contexto):
chaves |> left_join(atributos, by = "id")
left_join: added one column (nota_obs)
> rows only in chaves 2
> rows only in atributos (1)
> matched rows 4 (includes duplicates)
> ===
> rows total 6
bind_rows e bind_colsExemplo: empilhar e combinar
a <- tibble(id = 1:2, x = c("a","b"))
b <- tibble(id = 3:4, x = c("c","d"))
bind_rows(a, b)
bind_cols(tibble(u = 1:3), tibble(v = 4:6))
NA
tidyrpivot_longer / pivot_widerExemplo:
longo |> pivot_wider(names_from = prova, values_from = nota)
pivot_wider: reorganized (prova, nota) into (P1, P2) [was 6x3, now 3x3]
separate / uniteExemplo:
nest / unnestExemplo com penguins:
by_species$data
[[1]]
[[2]]
[[3]]
NA
stringrConceitos: str_to_lower,
str_trim, str_detect,
str_replace.
Exemplo: padronização de texto
tibble(nome = c(" ana ", "BRUNO", "cArLa?")) |>
mutate(
nome_limp = str_to_title(str_trim(nome)),
tem_interrogacao = str_detect(nome, "\\?"),
sem_interrogacao = str_replace(nome, "\\?", "")
)
mutate: new variable 'nome_limp' (character) with 3 unique values and 0% NA
new variable 'tem_interrogacao' (logical) with 2 unique values and 0% NA
new variable 'sem_interrogacao' (character) with 3 unique values and 0% NA
lubridateConceitos: parsing, extração de componentes, manipulação.
Exemplo: converter e extrair partes
tibble(texto = c("2025-08-21", "2025-08-22")) |>
mutate(
dt = parse_date_time(texto, "Y-m-d"),
ano = year(dt),
mes = month(dt),
Dia_do_ano = yday(dt),
semana2 = wday(dt))
mutate: new variable 'dt' (double) with 2 unique values and 0% NA
new variable 'ano' (integer) with one unique value and 0% NA
new variable 'mes' (integer) with one unique value and 0% NA
new variable 'Dia_do_ano' (integer) with 2 unique values and 0% NA
new variable 'semana2' (integer) with 2 unique values and 0% NA
ggplot2Exemplo: dispersão com linha de tendência
penguins |>
ggplot(aes(x = bill_length_mm, y = body_mass_g, color = species)) +
geom_point(alpha = 0.7, na.rm = TRUE) +
geom_smooth(method = "lm", se = FALSE) +
labs(title = "Massa vs. comprimento do bico — penguins",
x = "Comprimento do bico (mm)",
y = "Massa (g)")
`geom_smooth()` using formula = 'y ~ x'
Aviso: Removed 2 rows containing non-finite outside the scale range (`stat_smooth()`).
Exemplo: facetar por espécie
penguins |>
ggplot(aes(x = flipper_length_mm, y = body_mass_g)) +
geom_point(alpha = 0.6, na.rm = TRUE) +
facet_wrap(~species) +
labs(title = "Relação asa × massa por espécie")