Capítulo 29 Respostas
29.1 O pacote dplyr
29.1.1 Selecionando colunas
1. Teste aplicar a função glimpse()
do pacote `dplyr
à base
sw
. O que ela faz?
## Rows: 87
## Columns: 14
## $ name <chr> "Luke Skywalker", "C-3PO", "R2-D2", "Darth Vader", "Leia Or…
## $ height <int> 172, 167, 96, 202, 150, 178, 165, 97, 183, 182, 188, 180, 2…
## $ mass <dbl> 77.0, 75.0, 32.0, 136.0, 49.0, 120.0, 75.0, 32.0, 84.0, 77.…
## $ hair_color <chr> "blond", NA, NA, "none", "brown", "brown, grey", "brown", N…
## $ skin_color <chr> "fair", "gold", "white, blue", "white", "light", "light", "…
## $ eye_color <chr> "blue", "yellow", "red", "yellow", "brown", "blue", "blue",…
## $ birth_year <dbl> 19.0, 112.0, 33.0, 41.9, 19.0, 52.0, 47.0, NA, 24.0, 57.0, …
## $ sex <chr> "male", "none", "none", "male", "female", "male", "female",…
## $ gender <chr> "masculine", "masculine", "masculine", "masculine", "femini…
## $ homeworld <chr> "Tatooine", "Tatooine", "Naboo", "Tatooine", "Alderaan", "T…
## $ species <chr> "Human", "Droid", "Droid", "Human", "Human", "Human", "Huma…
## $ films <list> <"A New Hope", "The Empire Strikes Back", "Return of the J…
## $ vehicles <list> <"Snowspeeder", "Imperial Speeder Bike">, <>, <>, <>, "Imp…
## $ starships <list> <"X-wing", "Imperial shuttle">, <>, <>, "TIE Advanced x1",…
Mostra os nomes das variáveis, os tipos de dados e os primeiros valores de cada coluna em uma única visualização, tudo de forma horizontal.
2. Crie uma tabela com apenas as colunas name
, gender
, e
films
. Salve em um objeto chamado sw_simples
.
## # A tibble: 87 × 3
## name gender films
## <chr> <chr> <list>
## 1 Luke Skywalker masculine <chr [5]>
## 2 C-3PO masculine <chr [6]>
## 3 R2-D2 masculine <chr [7]>
## 4 Darth Vader masculine <chr [4]>
## 5 Leia Organa feminine <chr [5]>
## 6 Owen Lars masculine <chr [3]>
## 7 Beru Whitesun Lars feminine <chr [3]>
## 8 R5-D4 masculine <chr [1]>
## 9 Biggs Darklighter masculine <chr [1]>
## 10 Obi-Wan Kenobi masculine <chr [6]>
## # ℹ 77 more rows
3. Selecione apenas as colunas hair_color
, skin_color
e
eye_color
usando a função auxiliar contains()
.
## # A tibble: 87 × 3
## hair_color skin_color eye_color
## <chr> <chr> <chr>
## 1 blond fair blue
## 2 <NA> gold yellow
## 3 <NA> white, blue red
## 4 none white yellow
## 5 brown light brown
## 6 brown, grey light blue
## 7 brown light blue
## 8 <NA> white, red red
## 9 black light brown
## 10 auburn, white fair blue-gray
## # ℹ 77 more rows
4. Usando a função select()
(e suas funções auxiliares), escreva
códigos que retornem a base sw
sem as colunas hair_color
,
skin_color
e eye_color
. Escreva todas as soluções diferentes que
você conseguir pensar.
29.1.2 Ordenando a base
1. Ordene mass
em ordem crescente e birth_year
em ordem
decrescente e salve em um objeto chamado sw_ordenados
.
## # A tibble: 87 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Ratts T… 79 15 none grey, blue unknown NA male mascu…
## 2 Yoda 66 17 white green brown 896 male mascu…
## 3 Wicket … 88 20 brown brown brown 8 male mascu…
## 4 R2-D2 96 32 <NA> white, bl… red 33 none mascu…
## 5 R5-D4 97 32 <NA> white, red red NA none mascu…
## 6 Sebulba 112 40 none grey, red orange NA male mascu…
## 7 Padmé A… 185 45 brown light brown 46 fema… femin…
## 8 Dud Bolt 94 45 none blue, grey yellow NA male mascu…
## 9 Wat Tam… 193 48 none green, gr… unknown NA male mascu…
## 10 Sly Moo… 178 48 none pale white NA <NA> <NA>
## # ℹ 77 more rows
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>
2. Selecione apenas as colunas name
e birth_year
e então ordene
de forma decrescente pelo birth_year
.
29.1.3 Filtrando linhas
Utilize a base sw
nos exercícios a seguir.
1. Crie um objeto chamado humanos
apenas com personagens que sejam
humanos.
2. Crie um objeto chamado altos_fortes
com personagens que tenham
mais de 200 cm de altura e peso maior que 100 kg.
3. Retorne tabelas (tibbles
) apenas com:
a. Personagens humanos que nasceram antes de 100 anos antes da
batalha de Yavin (birth_year < 100
).
b. Personagens com cor light
ou red
.
c. Personagens com massa maior que 100 kg, ordenados de forma
decrescente por altura, mostrando apenas as colunas name
, mass
e
height
.
select(arrange(filter(sw, mass > 100), desc(height)), name, mass, height)
# usando o pipe
sw %>%
filter(mass > 100) %>%
arrange(desc(height)) %>%
select(name, mass, height)
d. Personagens que sejam “Humano” ou “Droid”, e tenham uma altura maior que 170 cm.
filter(sw, species == "Human" | species == "Droid", height > 170)
# usando o pipe
sw %>%
filter(species %in% c("Human", "Droid"), height > 170)
e. Personagens que não possuem informação tanto de altura quanto de massa, ou seja, possuem NA em ambas as colunas.
29.1.4 Modificando e criando novas colunas
1. Crie uma coluna chamada dif_peso_altura
(diferença entre altura
e peso) e salve a nova tabela em um objeto chamado sw_dif
. Em seguida,
filtre apenas os personagens que têm altura maior que o peso e ordene a
tabela por ordem crescente de dif_peso_altura
.
sw_dif <- mutate(sw, dif_peso_altura = height-mass)
arrange(filter(sw_dif, height > mass), dif_peso_altura)
# usando o pipe
sw_dif <- sw %>%
mutate(dif_peso_altura = height-mass)
sw_dif %>%
filter(height > mass) %>%
arrange(dif_peso_altura)
2. Fazendo apenas uma chamada da função mutate()
, crie as
seguintes colunas novas na base sw
:
a. indice_massa_altura
= mass
/ height
b. indice_massa_medio
= mean(mass, na.rm = TRUE)
c. indice_relativo
=
(indice_massa_altura - indice_massa_medio) / indice_massa_medio
d. acima_media
=
ifelse(indice_massa_altura > indice_massa_medio, “sim”, “não”)
29.1.5 Sumarizando a base
Utilize a base sw
nos exercícios a seguir.
1. Calcule a altura média e mediana dos personagens.
summarize(sw,
media_altura = mean(height, na.rm=TRUE),
mediana_altura = median(height, na.rm = TRUE))
## # A tibble: 1 × 2
## media_altura mediana_altura
## <dbl> <int>
## 1 175. 180
2. Calcule a massa média dos personagens cuja altura é maior que 175 cm.
## # A tibble: 1 × 1
## media_massa
## <dbl>
## 1 87.2
3. Apresente na mesma tabela a massa média dos personagens com altura menor que 175 cm e a massa média dos personagens com altura maior ou igual a 175 cm.
sw %>%
mutate(alturas = ifelse(height < 175, "menor 175", "maior 175")) %>%
filter(!is.na(height)) %>%
group_by(alturas) %>%
summarize(altura_media = mean(height, na.rm=TRUE)
)
## # A tibble: 2 × 2
## alturas altura_media
## <chr> <dbl>
## 1 maior 175 193.
## 2 menor 175 142.
4. Retorne tabelas (tibbles
) apenas com:
a. A altura média dos personagens por espécie.
## # A tibble: 38 × 2
## species altura_media
## <chr> <dbl>
## 1 Aleena 79
## 2 Besalisk 198
## 3 Cerean 198
## 4 Chagrian 196
## 5 Clawdite 168
## 6 Droid 131.
## 7 Dug 112
## 8 Ewok 88
## 9 Geonosian 183
## 10 Gungan 209.
## # ℹ 28 more rows
b. A massa média e mediana dos personagens por espécie.
sw %>%
filter(!is.na(mass)) %>%
group_by(species) %>%
summarize(massa_media = mean(mass, na.rm = TRUE),
massa_mediana = median(mass, na.rm = TRUE))
## # A tibble: 32 × 3
## species massa_media massa_mediana
## <chr> <dbl> <dbl>
## 1 Aleena 15 15
## 2 Besalisk 102 102
## 3 Cerean 82 82
## 4 Clawdite 55 55
## 5 Droid 69.8 53.5
## 6 Dug 40 40
## 7 Ewok 20 20
## 8 Geonosian 80 80
## 9 Gungan 74 74
## 10 Human 81.3 79
## # ℹ 22 more rows
c. Apenas o nome dos personagens que participaram de mais de 2 filmes.
## # A tibble: 87 × 1
## name
## <chr>
## 1 Luke Skywalker
## 2 C-3PO
## 3 R2-D2
## 4 Darth Vader
## 5 Leia Organa
## 6 Owen Lars
## 7 Beru Whitesun Lars
## 8 R5-D4
## 9 Biggs Darklighter
## 10 Obi-Wan Kenobi
## # ℹ 77 more rows