Manipulacao de dados em R - Prof Thiago Marques
Manipulação utilizando os pacotes da base do R
Instalando os pacotes e carregando
=c("tidyverse",
vetor_pacotes"rmdformats",
"DescTools") #Habilita manipulação de dados no R e o operador pipe
#install.packages(vetor_pacotes)
lapply(vetor_pacotes,
require, character.only = TRUE)
## Carregando pacotes exigidos: tidyverse
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.0 ✔ readr 2.1.4
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ ggplot2 3.4.1 ✔ tibble 3.2.1
## ✔ lubridate 1.9.2 ✔ tidyr 1.3.0
## ✔ purrr 1.0.1
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
## Carregando pacotes exigidos: rmdformats
##
## Carregando pacotes exigidos: DescTools
## [[1]]
## [1] TRUE
##
## [[2]]
## [1] TRUE
##
## [[3]]
## [1] TRUE
Conhecendo o banco de dados
= starwars
dados %>% head(10) dados
## # A tibble: 10 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Luke Sk… 172 77 blond fair blue 19 male mascu…
## 2 C-3PO 167 75 <NA> gold yellow 112 none mascu…
## 3 R2-D2 96 32 <NA> white, bl… red 33 none mascu…
## 4 Darth V… 202 136 none white yellow 41.9 male mascu…
## 5 Leia Or… 150 49 brown light brown 19 fema… femin…
## 6 Owen La… 178 120 brown, gr… light blue 52 male mascu…
## 7 Beru Wh… 165 75 brown light blue 47 fema… femin…
## 8 R5-D4 97 32 <NA> white, red red NA none mascu…
## 9 Biggs D… 183 84 black light brown 24 male mascu…
## 10 Obi-Wan… 182 77 auburn, w… fair blue-gray 57 male mascu…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>
Conhecendo o banco de dados ( View() )
Conhecendo o banco de dados (6 Primeiras linhas)
head(dados)
## # A tibble: 6 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Luke Sky… 172 77 blond fair blue 19 male mascu…
## 2 C-3PO 167 75 <NA> gold yellow 112 none mascu…
## 3 R2-D2 96 32 <NA> white, bl… red 33 none mascu…
## 4 Darth Va… 202 136 none white yellow 41.9 male mascu…
## 5 Leia Org… 150 49 brown light brown 19 fema… femin…
## 6 Owen Lars 178 120 brown, gr… light blue 52 male mascu…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>
Conhecendo o banco de dados (6 Últimas linhas)
tail(dados)
## # A tibble: 6 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Finn NA NA black dark dark NA male mascu…
## 2 Rey NA NA brown light hazel NA fema… femin…
## 3 Poe Dame… NA NA brown light brown NA male mascu…
## 4 BB8 NA NA none none black NA none mascu…
## 5 Captain … NA NA unknown unknown unknown NA <NA> <NA>
## 6 Padmé Am… 165 45 brown light brown 46 fema… femin…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>
Conhecendo o nome das colunas
names(dados)
## [1] "name" "height" "mass" "hair_color" "skin_color"
## [6] "eye_color" "birth_year" "sex" "gender" "homeworld"
## [11] "species" "films" "vehicles" "starships"
Observando quantas linhas e colunas têm o banco
dim(dados)
## [1] 87 14
Observando quantas linhas têm o banco
dim(dados)[1]
## [1] 87
Observando quantas colunas têm o banco
dim(dados)[2]
## [1] 14
Observando a Estrutura do banco e tipos de variáveis
glimpse(dados)
## 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> <"The Empire Strikes Back", "Revenge of the Sith", "Return…
## $ vehicles <list> <"Snowspeeder", "Imperial Speeder Bike">, <>, <>, <>, "Imp…
## $ starships <list> <"X-wing", "Imperial shuttle">, <>, <>, "TIE Advanced x1",…
Resumo descritivo das variáveis
summary(dados[1:11])
## name height mass hair_color
## Length:87 Min. : 66.0 Min. : 15.00 Length:87
## Class :character 1st Qu.:167.0 1st Qu.: 55.60 Class :character
## Mode :character Median :180.0 Median : 79.00 Mode :character
## Mean :174.4 Mean : 97.31
## 3rd Qu.:191.0 3rd Qu.: 84.50
## Max. :264.0 Max. :1358.00
## NA's :6 NA's :28
## skin_color eye_color birth_year sex
## Length:87 Length:87 Min. : 8.00 Length:87
## Class :character Class :character 1st Qu.: 35.00 Class :character
## Mode :character Mode :character Median : 52.00 Mode :character
## Mean : 87.57
## 3rd Qu.: 72.00
## Max. :896.00
## NA's :44
## gender homeworld species
## Length:87 Length:87 Length:87
## Class :character Class :character Class :character
## Mode :character Mode :character Mode :character
##
##
##
##
Filtros, seleções, ordenação e transformações com dplyr
Selecionando colunas do df/tible
= dados %>% select(name,height,hair_color)
dados_select %>% head(10) dados_select
## # A tibble: 10 × 3
## name height hair_color
## <chr> <int> <chr>
## 1 Luke Skywalker 172 blond
## 2 C-3PO 167 <NA>
## 3 R2-D2 96 <NA>
## 4 Darth Vader 202 none
## 5 Leia Organa 150 brown
## 6 Owen Lars 178 brown, grey
## 7 Beru Whitesun lars 165 brown
## 8 R5-D4 97 <NA>
## 9 Biggs Darklighter 183 black
## 10 Obi-Wan Kenobi 182 auburn, white
Selecionando uma coluna do df/tible
= dados %>% select(name)
dados_select dados_select
## # 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
#class(dados_select)
Selecionando colunas do df/tible
= dados %>% pull(name)
dados_pull dados_pull
## [1] "Luke Skywalker" "C-3PO" "R2-D2"
## [4] "Darth Vader" "Leia Organa" "Owen Lars"
## [7] "Beru Whitesun lars" "R5-D4" "Biggs Darklighter"
## [10] "Obi-Wan Kenobi" "Anakin Skywalker" "Wilhuff Tarkin"
## [13] "Chewbacca" "Han Solo" "Greedo"
## [16] "Jabba Desilijic Tiure" "Wedge Antilles" "Jek Tono Porkins"
## [19] "Yoda" "Palpatine" "Boba Fett"
## [22] "IG-88" "Bossk" "Lando Calrissian"
## [25] "Lobot" "Ackbar" "Mon Mothma"
## [28] "Arvel Crynyd" "Wicket Systri Warrick" "Nien Nunb"
## [31] "Qui-Gon Jinn" "Nute Gunray" "Finis Valorum"
## [34] "Jar Jar Binks" "Roos Tarpals" "Rugor Nass"
## [37] "Ric Olié" "Watto" "Sebulba"
## [40] "Quarsh Panaka" "Shmi Skywalker" "Darth Maul"
## [43] "Bib Fortuna" "Ayla Secura" "Dud Bolt"
## [46] "Gasgano" "Ben Quadinaros" "Mace Windu"
## [49] "Ki-Adi-Mundi" "Kit Fisto" "Eeth Koth"
## [52] "Adi Gallia" "Saesee Tiin" "Yarael Poof"
## [55] "Plo Koon" "Mas Amedda" "Gregar Typho"
## [58] "Cordé" "Cliegg Lars" "Poggle the Lesser"
## [61] "Luminara Unduli" "Barriss Offee" "Dormé"
## [64] "Dooku" "Bail Prestor Organa" "Jango Fett"
## [67] "Zam Wesell" "Dexter Jettster" "Lama Su"
## [70] "Taun We" "Jocasta Nu" "Ratts Tyerell"
## [73] "R4-P17" "Wat Tambor" "San Hill"
## [76] "Shaak Ti" "Grievous" "Tarfful"
## [79] "Raymus Antilles" "Sly Moore" "Tion Medon"
## [82] "Finn" "Rey" "Poe Dameron"
## [85] "BB8" "Captain Phasma" "Padmé Amidala"
#class(dados_pull)
Selecionando colunas do df/tible começando com uma letra h
= dados %>% select(starts_with("h"))
dados_h %>% head(10) dados_h
## # A tibble: 10 × 3
## height hair_color homeworld
## <int> <chr> <chr>
## 1 172 blond Tatooine
## 2 167 <NA> Tatooine
## 3 96 <NA> Naboo
## 4 202 none Tatooine
## 5 150 brown Alderaan
## 6 178 brown, grey Tatooine
## 7 165 brown Tatooine
## 8 97 <NA> Tatooine
## 9 183 black Tatooine
## 10 182 auburn, white Stewjon
Filtrando linhas do df/tible do planeta Tatooine
= dados %>% filter(homeworld=="Tatooine")
dados_tatoine dados_tatoine
## # A tibble: 10 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Luke Sk… 172 77 blond fair blue 19 male mascu…
## 2 C-3PO 167 75 <NA> gold yellow 112 none mascu…
## 3 Darth V… 202 136 none white yellow 41.9 male mascu…
## 4 Owen La… 178 120 brown, gr… light blue 52 male mascu…
## 5 Beru Wh… 165 75 brown light blue 47 fema… femin…
## 6 R5-D4 97 32 <NA> white, red red NA none mascu…
## 7 Biggs D… 183 84 black light brown 24 male mascu…
## 8 Anakin … 188 84 blond fair blue 41.9 male mascu…
## 9 Shmi Sk… 163 NA black fair brown 72 fema… femin…
## 10 Cliegg … 183 NA brown fair blue 82 male mascu…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>
Filtrando linhas do df/tible do planeta tatooine e olhos azuis
= dados %>% filter(homeworld=="Tatooine" & hair_color=="black")
dados_tatoine_black dados_tatoine_black
## # A tibble: 2 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Biggs Da… 183 84 black light brown 24 male mascu…
## 2 Shmi Sky… 163 NA black fair brown 72 fema… femin…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>
Filtrando observações distintas da coluna hair_color
= dados_tatoine_black %>% distinct(hair_color)
dados_tatoine_black_distinct dados_tatoine_black_distinct
## # A tibble: 1 × 1
## hair_color
## <chr>
## 1 black
Ordenando observações da coluna altura (Ordem crescente)
= dados %>% arrange(height)
dados_ord_height %>% head(10) dados_ord_height
## # A tibble: 10 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Yoda 66 17 white green brown 896 male mascu…
## 2 Ratts T… 79 15 none grey, blue unknown NA male mascu…
## 3 Wicket … 88 20 brown brown brown 8 male mascu…
## 4 Dud Bolt 94 45 none blue, grey yellow NA male mascu…
## 5 R2-D2 96 32 <NA> white, bl… red 33 none mascu…
## 6 R4-P17 96 NA none silver, r… red, blue NA none femin…
## 7 R5-D4 97 32 <NA> white, red red NA none mascu…
## 8 Sebulba 112 40 none grey, red orange NA male mascu…
## 9 Gasgano 122 NA none white, bl… black NA male mascu…
## 10 Watto 137 NA black blue, grey yellow NA male mascu…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>
Ordenando observações da coluna altura (Ordem decrescente)
= dados %>% arrange(desc(height))
dados_ord_height %>% head(10) dados_ord_height
## # A tibble: 10 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Yarael … 264 NA none white yellow NA male mascu…
## 2 Tarfful 234 136 brown brown blue NA male mascu…
## 3 Lama Su 229 88 none grey black NA male mascu…
## 4 Chewbac… 228 112 brown unknown blue 200 male mascu…
## 5 Roos Ta… 224 82 none grey orange NA male mascu…
## 6 Grievous 216 159 none brown, wh… green, y… NA male mascu…
## 7 Taun We 213 NA none grey black NA fema… femin…
## 8 Rugor N… 206 NA none green orange NA male mascu…
## 9 Tion Me… 206 80 none grey black NA male mascu…
## 10 Darth V… 202 136 none white yellow 41.9 male mascu…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>
Adicionando colunas com mutate (Adicionando coluna e mantendo demais)
= dados %>% mutate(coluna_nova_metros=height/mass)
dados_mutate %>% head(10) dados_mutate
## # A tibble: 10 × 15
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Luke Sk… 172 77 blond fair blue 19 male mascu…
## 2 C-3PO 167 75 <NA> gold yellow 112 none mascu…
## 3 R2-D2 96 32 <NA> white, bl… red 33 none mascu…
## 4 Darth V… 202 136 none white yellow 41.9 male mascu…
## 5 Leia Or… 150 49 brown light brown 19 fema… femin…
## 6 Owen La… 178 120 brown, gr… light blue 52 male mascu…
## 7 Beru Wh… 165 75 brown light blue 47 fema… femin…
## 8 R5-D4 97 32 <NA> white, red red NA none mascu…
## 9 Biggs D… 183 84 black light brown 24 male mascu…
## 10 Obi-Wan… 182 77 auburn, w… fair blue-gray 57 male mascu…
## # ℹ 6 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>, coluna_nova_metros <dbl>
Adicionando colunas com transmute (Adicionando coluna e excluindo demais)
= dados %>% transmute(coluna_nova_metros=height/mass)
dados_transmute %>% head(10) dados_transmute
## # A tibble: 10 × 1
## coluna_nova_metros
## <dbl>
## 1 2.23
## 2 2.23
## 3 3
## 4 1.49
## 5 3.06
## 6 1.48
## 7 2.2
## 8 3.03
## 9 2.18
## 10 2.36
Renomeando colunas com rename
= dados_mutate %>% rename(height_m=coluna_nova_metros)
dados_mutate %>% head(10) dados_mutate
## # A tibble: 10 × 15
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Luke Sk… 172 77 blond fair blue 19 male mascu…
## 2 C-3PO 167 75 <NA> gold yellow 112 none mascu…
## 3 R2-D2 96 32 <NA> white, bl… red 33 none mascu…
## 4 Darth V… 202 136 none white yellow 41.9 male mascu…
## 5 Leia Or… 150 49 brown light brown 19 fema… femin…
## 6 Owen La… 178 120 brown, gr… light blue 52 male mascu…
## 7 Beru Wh… 165 75 brown light blue 47 fema… femin…
## 8 R5-D4 97 32 <NA> white, red red NA none mascu…
## 9 Biggs D… 183 84 black light brown 24 male mascu…
## 10 Obi-Wan… 182 77 auburn, w… fair blue-gray 57 male mascu…
## # ℹ 6 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>, height_m <dbl>
Adicionando colunas com add_column (por referência às colunas)
= dados_mutate %>% add_column(coluna_nova_metros2=1:87 ,.before=2)
dados_mutate %>% head(10) dados_mutate
## # A tibble: 10 × 16
## name coluna_nova_metros2 height mass hair_color skin_color eye_color
## <chr> <int> <int> <dbl> <chr> <chr> <chr>
## 1 Luke Skywal… 1 172 77 blond fair blue
## 2 C-3PO 2 167 75 <NA> gold yellow
## 3 R2-D2 3 96 32 <NA> white, bl… red
## 4 Darth Vader 4 202 136 none white yellow
## 5 Leia Organa 5 150 49 brown light brown
## 6 Owen Lars 6 178 120 brown, gr… light blue
## 7 Beru Whites… 7 165 75 brown light blue
## 8 R5-D4 8 97 32 <NA> white, red red
## 9 Biggs Darkl… 9 183 84 black light brown
## 10 Obi-Wan Ken… 10 182 77 auburn, w… fair blue-gray
## # ℹ 9 more variables: birth_year <dbl>, sex <chr>, gender <chr>,
## # homeworld <chr>, species <chr>, films <list>, vehicles <list>,
## # starships <list>, height_m <dbl>
Excluindo colunas
= dados_mutate %>% select(-c("coluna_nova_metros2"))
dados_mutate %>% head(10) dados_mutate
## # A tibble: 10 × 15
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Luke Sk… 172 77 blond fair blue 19 male mascu…
## 2 C-3PO 167 75 <NA> gold yellow 112 none mascu…
## 3 R2-D2 96 32 <NA> white, bl… red 33 none mascu…
## 4 Darth V… 202 136 none white yellow 41.9 male mascu…
## 5 Leia Or… 150 49 brown light brown 19 fema… femin…
## 6 Owen La… 178 120 brown, gr… light blue 52 male mascu…
## 7 Beru Wh… 165 75 brown light blue 47 fema… femin…
## 8 R5-D4 97 32 <NA> white, red red NA none mascu…
## 9 Biggs D… 183 84 black light brown 24 male mascu…
## 10 Obi-Wan… 182 77 auburn, w… fair blue-gray 57 male mascu…
## # ℹ 6 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>, height_m <dbl>
Resumindo seus dados com funções de agregação de contagem
= dados %>% select(eye_color,skin_color) %>% filter(skin_color=="dark") %>% summarize(n())
dados_cont dados_cont
## # A tibble: 1 × 1
## `n()`
## <int>
## 1 6
Resumindo seus dados com funções de agregação de contagem por categoria
= dados %>% select(eye_color,skin_color) %>% group_by(skin_color) %>% summarize(n())
dados_agrupados dados_agrupados
## # A tibble: 31 × 2
## skin_color `n()`
## <chr> <int>
## 1 blue 2
## 2 blue, grey 2
## 3 brown 4
## 4 brown mottle 1
## 5 brown, white 1
## 6 dark 6
## 7 fair 17
## 8 fair, green, yellow 1
## 9 gold 1
## 10 green 6
## # ℹ 21 more rows
Resumindo seus dados com funções de agregação da média por categoria
= dados %>% select(eye_color,skin_color,height) %>% group_by(skin_color) %>% summarize(mean(height))
dados_agrupados dados_agrupados
## # A tibble: 31 × 2
## skin_color `mean(height)`
## <chr> <dbl>
## 1 blue 187
## 2 blue, grey 116.
## 3 brown 173.
## 4 brown mottle 180
## 5 brown, white 216
## 6 dark NA
## 7 fair NA
## 8 fair, green, yellow 168
## 9 gold 167
## 10 green 169
## # ℹ 21 more rows
Resumindo seus dados com funções de agregação da média por categoria e top 5
= dados %>% select(eye_color,skin_color,height) %>% group_by(skin_color) %>% summarize(mean(height)) %>% top_n(5) dados_agrupados
## Selecting by mean(height)
dados_agrupados
## # A tibble: 5 × 2
## skin_color `mean(height)`
## <chr> <dbl>
## 1 brown, white 216
## 2 green, grey 193
## 3 grey 204.
## 4 metal 200
## 5 white 233
Trabalhando com valores faltantes no R (base e tidy)
Diferença entre os valores NA,NULL e NAN
- NA para o R nada mais é do que o valor faltante,
- NULL (nulo) representa a ausência de um objeto.
- NAN quando é impossível esse valor acontecer (divisão por zero, por exemplo)
Verificando Valores faltantes da variável hair_color
%>% select(hair_color) %>% is.na() dados
## hair_color
## [1,] FALSE
## [2,] TRUE
## [3,] TRUE
## [4,] FALSE
## [5,] FALSE
## [6,] FALSE
## [7,] FALSE
## [8,] TRUE
## [9,] FALSE
## [10,] FALSE
## [11,] FALSE
## [12,] FALSE
## [13,] FALSE
## [14,] FALSE
## [15,] TRUE
## [16,] TRUE
## [17,] FALSE
## [18,] FALSE
## [19,] FALSE
## [20,] FALSE
## [21,] FALSE
## [22,] FALSE
## [23,] FALSE
## [24,] FALSE
## [25,] FALSE
## [26,] FALSE
## [27,] FALSE
## [28,] FALSE
## [29,] FALSE
## [30,] FALSE
## [31,] FALSE
## [32,] FALSE
## [33,] FALSE
## [34,] FALSE
## [35,] FALSE
## [36,] FALSE
## [37,] FALSE
## [38,] FALSE
## [39,] FALSE
## [40,] FALSE
## [41,] FALSE
## [42,] FALSE
## [43,] FALSE
## [44,] FALSE
## [45,] FALSE
## [46,] FALSE
## [47,] FALSE
## [48,] FALSE
## [49,] FALSE
## [50,] FALSE
## [51,] FALSE
## [52,] FALSE
## [53,] FALSE
## [54,] FALSE
## [55,] FALSE
## [56,] FALSE
## [57,] FALSE
## [58,] FALSE
## [59,] FALSE
## [60,] FALSE
## [61,] FALSE
## [62,] FALSE
## [63,] FALSE
## [64,] FALSE
## [65,] FALSE
## [66,] FALSE
## [67,] FALSE
## [68,] FALSE
## [69,] FALSE
## [70,] FALSE
## [71,] FALSE
## [72,] FALSE
## [73,] FALSE
## [74,] FALSE
## [75,] FALSE
## [76,] FALSE
## [77,] FALSE
## [78,] FALSE
## [79,] FALSE
## [80,] FALSE
## [81,] FALSE
## [82,] FALSE
## [83,] FALSE
## [84,] FALSE
## [85,] FALSE
## [86,] FALSE
## [87,] FALSE
Contando valores faltantes da variável hair_color
%>% select(hair_color) %>% is.na() %>% sum() dados
## [1] 5
Verificando Valores não faltantes da variável hair_color
%>% select(hair_color) %>% complete.cases() dados
## [1] TRUE FALSE FALSE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE
## [13] TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [25] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [37] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [49] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [61] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [73] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
## [85] TRUE TRUE TRUE
Contando valores não faltantes da variável hair_color
%>% select(hair_color) %>% complete.cases() %>% sum() dados
## [1] 82
Eliminando os NA´S da variável hair_color
%>% select(hair_color) %>% na.omit() dados
## # A tibble: 82 × 1
## hair_color
## <chr>
## 1 blond
## 2 none
## 3 brown
## 4 brown, grey
## 5 brown
## 6 black
## 7 auburn, white
## 8 blond
## 9 auburn, grey
## 10 brown
## # ℹ 72 more rows
Contando a quantidade de NA´s da variável hair_color após a remoção
%>% select(hair_color) %>% drop_na() %>% is.na() %>% sum() dados
## [1] 0
Contabilizando o NA de todas as variáveis do banco
= dados %>% summarise_all(~sum(is.na(.)))
resumo_nas resumo_nas
## # A tibble: 1 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <int> <int> <int> <int> <int> <int> <int> <int> <int>
## 1 0 6 28 5 0 0 44 4 4
## # ℹ 5 more variables: homeworld <int>, species <int>, films <int>,
## # vehicles <int>, starships <int>
Preenche com o valor anterior ou posterior
= dados %>% fill(sex)
dados_sexo_preenchidos %>% head(10) dados_sexo_preenchidos
## # A tibble: 10 × 14
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Luke Sk… 172 77 blond fair blue 19 male mascu…
## 2 C-3PO 167 75 <NA> gold yellow 112 none mascu…
## 3 R2-D2 96 32 <NA> white, bl… red 33 none mascu…
## 4 Darth V… 202 136 none white yellow 41.9 male mascu…
## 5 Leia Or… 150 49 brown light brown 19 fema… femin…
## 6 Owen La… 178 120 brown, gr… light blue 52 male mascu…
## 7 Beru Wh… 165 75 brown light blue 47 fema… femin…
## 8 R5-D4 97 32 <NA> white, red red NA none mascu…
## 9 Biggs D… 183 84 black light brown 24 male mascu…
## 10 Obi-Wan… 182 77 auburn, w… fair blue-gray 57 male mascu…
## # ℹ 5 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>
Construindo a função da Moda
<- function(x) {
mode <- unique(x)
ux which.max(tabulate(match(x, ux)))]
ux[ }
Preenche com o valor desejado: A moda nesse caso
= dados %>% mutate(nova_var = replace_na(sex,mode(sex)))
dados_sexo_preenchidos_moda %>% head(10) dados_sexo_preenchidos_moda
## # A tibble: 10 × 15
## name height mass hair_color skin_color eye_color birth_year sex gender
## <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 Luke Sk… 172 77 blond fair blue 19 male mascu…
## 2 C-3PO 167 75 <NA> gold yellow 112 none mascu…
## 3 R2-D2 96 32 <NA> white, bl… red 33 none mascu…
## 4 Darth V… 202 136 none white yellow 41.9 male mascu…
## 5 Leia Or… 150 49 brown light brown 19 fema… femin…
## 6 Owen La… 178 120 brown, gr… light blue 52 male mascu…
## 7 Beru Wh… 165 75 brown light blue 47 fema… femin…
## 8 R5-D4 97 32 <NA> white, red red NA none mascu…
## 9 Biggs D… 183 84 black light brown 24 male mascu…
## 10 Obi-Wan… 182 77 auburn, w… fair blue-gray 57 male mascu…
## # ℹ 6 more variables: homeworld <chr>, species <chr>, films <list>,
## # vehicles <list>, starships <list>, nova_var <chr>
Selecionando algumas variáveis e descartando NAS
= dados %>% select(name,height,mass,hair_color,skin_color,eye_color,sex,gender,homeworld, species) %>% na.omit() dados_select
Excluimos 37 linhas com NA´S e ficamos com 50
= dados %>% select(name,height,mass,hair_color,skin_color,eye_color,sex,gender,homeworld, species) %>% na.omit() dados_select_sem_na
Faxina de dados com tidy
Princípios tidy
- Cada coluna é uma variável;
- cada linha é uma observação;
Reparem que a coluna hair_color não obedece o 2).
Utilizando separate para transformar em tidy
= dados_select_sem_na %>% separate(hair_color,c("hair_color1","hair_color2",sep=",")) dados_select_sem_na_sep
## Warning: Expected 3 pieces. Missing pieces filled with `NA` in 50 rows [1, 2, 3, 4, 5,
## 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...].
Confirmando hair_color1
table(dados_select_sem_na_sep$hair_color1)
##
## auburn black blond blonde brown grey none white
## 1 7 2 1 11 1 25 2
Confirmando hair_color2
table(dados_select_sem_na_sep$hair_color2)
##
## grey white
## 1 1
Reorganizando no formato long com gather para algumas variáveis
= dados_select_sem_na_sep %>% select(hair_color1,hair_color2,homeworld) %>% gather(nomevar_cabelo,valoresvar_cabelo,hair_color1:hair_color2) dados_select_sem_na_sep_gather
Reorganizando no formato long com gather para o banco todo
= dados_select_sem_na_sep %>% gather(nomevar_cabelo,valoresvar_cabelo,hair_color1:hair_color2) dados_select_sem_na_sep_gather
Junção de tabelas no R
Criando ID´S únicos para os nomes
= dados_select_sem_na_sep %>% mutate(id_nome = 1:50) dados_select_sem_na_sep
Criando uma tabela com nome, sexo e ID
set.seed(1234)
= dados_select_sem_na_sep %>% select(id_nome,name,sex) %>% sample_n(10) %>% arrange(id_nome) tab1_sexo
Criando uma tabela com nome e cor dos olhos com 10 linhas sorteadas aleatoriamente
set.seed(1235)
= dados_select_sem_na_sep %>% select(id_nome,hair_color1) %>% sample_n(10) %>% arrange(id_nome) tab2_cor_cabelo
IDS dos nomes na interseção entre a tabela de sexo e cor do cabelo
intersect(tab1_sexo$id_nome,tab2_cor_cabelo$id_nome)
## [1] 28 37
Interseção entre a tabela de sexo e cor do cabelo
= inner_join(tab1_sexo,tab2_cor_cabelo,by=c("id_nome"="id_nome")) tab_inner
IDS dos nomes que tem na tabela sexo e que não tem na tabela cor de cabelo
setdiff(tab1_sexo$id_nome,tab2_cor_cabelo$id_nome)
## [1] 4 5 9 16 22 38 44 49
Trazendo tudo que tem na tabela de sexo e não tem em cor do cabelo
= left_join(tab1_sexo,tab2_cor_cabelo,by=c("id_nome"="id_nome")) tab_left
IDS dos nomes que tem na tabela cor de cabelo e que não tem na tabela sexo
setdiff(tab2_cor_cabelo$id_nome,tab1_sexo$id_nome)
## [1] 3 12 13 14 27 35 36 47
Trouxe tudo que tem na tabela de cor do cabeloe não tem em sexo
= right_join(tab1_sexo,tab2_cor_cabelo,by=c("id_nome"="id_nome")) tab_right
Trazendo tudo que tem na tabela de cor do cabeloe não tem em sexo
= right_join(tab1_sexo,tab2_cor_cabelo,by=c("id_nome"="id_nome")) tab_right
Trazendo tudo que tem em ambas as tabelas
= full_join(tab1_sexo,tab2_cor_cabelo,by=c("id_nome"="id_nome")) tab_fulljoin
Criando gráficos profissionais no R
Gráficos Estatísticos para variáveis Qualitativas - R
Instalando e carregando bibliotecas
#install.páckages("devtools")
#install_github("juba/rmdformats",force=TRUE)
#install_github("glin/reactable",force=TRUE)
=c( "ggplot2", #Melhor pacote do R para gráficos
vetor_pacotes"scales", #transformar variáveis e alterar a escala
"plotly", #torna os gráficos interativos
"gridExtra", #habilita o layout personalzidado - gráficos ggplot
"dplyr", #Habilita manipulação de dados no R e o operador pipe
"kableExtra" #Habilita tabelas mais profissionais no R
)#install.packages(vetor_pacotes)
lapply(vetor_pacotes,
require, character.only = TRUE)
## Carregando pacotes exigidos: scales
##
## Attaching package: 'scales'
## The following object is masked from 'package:purrr':
##
## discard
## The following object is masked from 'package:readr':
##
## col_factor
## Carregando pacotes exigidos: plotly
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
## Carregando pacotes exigidos: gridExtra
##
## Attaching package: 'gridExtra'
## The following object is masked from 'package:dplyr':
##
## combine
## Carregando pacotes exigidos: kableExtra
##
## Attaching package: 'kableExtra'
## The following object is masked from 'package:dplyr':
##
## group_rows
## [[1]]
## [1] TRUE
##
## [[2]]
## [1] TRUE
##
## [[3]]
## [1] TRUE
##
## [[4]]
## [1] TRUE
##
## [[5]]
## [1] TRUE
##
## [[6]]
## [1] TRUE
Criando o banco de dados
=c("M","F")
sexo=c("Preto","Castanho","Azul","Verde")
cor=c("Fumante","Não Fumante")
cigarro=c("Doente","Sadio")
doente=c("Solteiro(a)","Casado(a)")
estado_civil
=sample(sexo,size=100, replace=TRUE)
a_sexo=sample(cor,size=100, replace=TRUE)
a_cor_olhos=sample(cigarro,size=100, replace=TRUE)
a_fumante=sample(doente,size=100, replace=TRUE)
a_doente=sample(estado_civil,size=100, replace=TRUE)
a_estado_civil=ifelse(a_estado_civil=="Solteiro(a)","1","0")
a_dummy_estado_civil
<<- data.frame(a_sexo,
variaveis_categoricas_nominais
a_cor_olhos,
a_fumante,
a_doente,
a_estado_civil,
a_dummy_estado_civil)
%>% kbl %>% kable_material_dark(full_width = F) variaveis_categoricas_nominais
a_sexo | a_cor_olhos | a_fumante | a_doente | a_estado_civil | a_dummy_estado_civil |
---|---|---|---|---|---|
F | Verde | Não Fumante | Doente | Solteiro(a) | 1 |
M | Castanho | Não Fumante | Doente | Solteiro(a) | 1 |
F | Castanho | Não Fumante | Sadio | Casado(a) | 0 |
M | Verde | Fumante | Doente | Solteiro(a) | 1 |
F | Azul | Fumante | Doente | Solteiro(a) | 1 |
F | Azul | Não Fumante | Sadio | Casado(a) | 0 |
F | Azul | Não Fumante | Sadio | Solteiro(a) | 1 |
F | Azul | Não Fumante | Doente | Solteiro(a) | 1 |
F | Preto | Não Fumante | Sadio | Casado(a) | 0 |
M | Castanho | Fumante | Doente | Casado(a) | 0 |
F | Azul | Fumante | Sadio | Casado(a) | 0 |
F | Castanho | Não Fumante | Sadio | Casado(a) | 0 |
M | Preto | Não Fumante | Sadio | Solteiro(a) | 1 |
F | Preto | Fumante | Sadio | Solteiro(a) | 1 |
M | Azul | Não Fumante | Sadio | Solteiro(a) | 1 |
M | Castanho | Fumante | Sadio | Casado(a) | 0 |
M | Preto | Fumante | Sadio | Solteiro(a) | 1 |
F | Preto | Não Fumante | Doente | Casado(a) | 0 |
F | Preto | Não Fumante | Doente | Casado(a) | 0 |
F | Azul | Não Fumante | Sadio | Solteiro(a) | 1 |
M | Verde | Não Fumante | Sadio | Casado(a) | 0 |
F | Preto | Fumante | Sadio | Solteiro(a) | 1 |
F | Azul | Não Fumante | Doente | Solteiro(a) | 1 |
M | Castanho | Fumante | Doente | Casado(a) | 0 |
M | Azul | Fumante | Doente | Solteiro(a) | 1 |
F | Castanho | Fumante | Doente | Solteiro(a) | 1 |
F | Verde | Não Fumante | Doente | Solteiro(a) | 1 |
M | Castanho | Fumante | Doente | Solteiro(a) | 1 |
M | Preto | Não Fumante | Doente | Casado(a) | 0 |
F | Verde | Não Fumante | Sadio | Solteiro(a) | 1 |
F | Verde | Fumante | Sadio | Solteiro(a) | 1 |
F | Azul | Não Fumante | Doente | Solteiro(a) | 1 |
M | Verde | Fumante | Doente | Solteiro(a) | 1 |
F | Azul | Fumante | Sadio | Casado(a) | 0 |
M | Preto | Não Fumante | Sadio | Casado(a) | 0 |
F | Castanho | Fumante | Doente | Solteiro(a) | 1 |
M | Castanho | Fumante | Doente | Casado(a) | 0 |
M | Verde | Fumante | Sadio | Solteiro(a) | 1 |
M | Castanho | Fumante | Doente | Solteiro(a) | 1 |
M | Preto | Fumante | Doente | Solteiro(a) | 1 |
M | Preto | Fumante | Doente | Solteiro(a) | 1 |
M | Castanho | Fumante | Doente | Casado(a) | 0 |
F | Castanho | Não Fumante | Sadio | Solteiro(a) | 1 |
M | Azul | Não Fumante | Sadio | Casado(a) | 0 |
M | Preto | Não Fumante | Sadio | Solteiro(a) | 1 |
F | Azul | Fumante | Sadio | Solteiro(a) | 1 |
F | Azul | Não Fumante | Sadio | Solteiro(a) | 1 |
M | Preto | Fumante | Doente | Casado(a) | 0 |
M | Preto | Não Fumante | Sadio | Solteiro(a) | 1 |
F | Verde | Fumante | Sadio | Solteiro(a) | 1 |
M | Castanho | Não Fumante | Sadio | Solteiro(a) | 1 |
M | Castanho | Fumante | Doente | Casado(a) | 0 |
M | Castanho | Não Fumante | Sadio | Solteiro(a) | 1 |
F | Azul | Fumante | Sadio | Solteiro(a) | 1 |
M | Preto | Não Fumante | Doente | Casado(a) | 0 |
M | Azul | Fumante | Doente | Solteiro(a) | 1 |
F | Preto | Não Fumante | Sadio | Casado(a) | 0 |
F | Preto | Fumante | Doente | Solteiro(a) | 1 |
M | Preto | Fumante | Sadio | Casado(a) | 0 |
M | Preto | Não Fumante | Sadio | Casado(a) | 0 |
F | Azul | Não Fumante | Sadio | Solteiro(a) | 1 |
M | Preto | Não Fumante | Doente | Casado(a) | 0 |
F | Preto | Não Fumante | Sadio | Casado(a) | 0 |
M | Azul | Não Fumante | Sadio | Solteiro(a) | 1 |
M | Castanho | Fumante | Sadio | Solteiro(a) | 1 |
M | Preto | Não Fumante | Doente | Casado(a) | 0 |
F | Verde | Não Fumante | Sadio | Solteiro(a) | 1 |
M | Preto | Fumante | Sadio | Casado(a) | 0 |
M | Azul | Não Fumante | Sadio | Solteiro(a) | 1 |
F | Preto | Fumante | Sadio | Casado(a) | 0 |
M | Azul | Não Fumante | Sadio | Solteiro(a) | 1 |
M | Verde | Não Fumante | Sadio | Solteiro(a) | 1 |
M | Preto | Fumante | Doente | Casado(a) | 0 |
M | Azul | Não Fumante | Sadio | Casado(a) | 0 |
F | Azul | Fumante | Doente | Casado(a) | 0 |
F | Preto | Fumante | Doente | Solteiro(a) | 1 |
M | Castanho | Não Fumante | Doente | Solteiro(a) | 1 |
F | Verde | Fumante | Doente | Casado(a) | 0 |
F | Preto | Não Fumante | Sadio | Casado(a) | 0 |
M | Verde | Não Fumante | Doente | Casado(a) | 0 |
F | Preto | Não Fumante | Sadio | Casado(a) | 0 |
M | Preto | Fumante | Doente | Casado(a) | 0 |
M | Azul | Fumante | Sadio | Solteiro(a) | 1 |
F | Azul | Não Fumante | Sadio | Casado(a) | 0 |
M | Preto | Não Fumante | Doente | Solteiro(a) | 1 |
F | Azul | Fumante | Doente | Solteiro(a) | 1 |
F | Azul | Fumante | Doente | Casado(a) | 0 |
M | Preto | Fumante | Doente | Casado(a) | 0 |
F | Castanho | Fumante | Sadio | Casado(a) | 0 |
F | Azul | Fumante | Sadio | Casado(a) | 0 |
F | Verde | Não Fumante | Doente | Solteiro(a) | 1 |
F | Verde | Não Fumante | Doente | Solteiro(a) | 1 |
F | Castanho | Não Fumante | Doente | Casado(a) | 0 |
F | Azul | Fumante | Sadio | Solteiro(a) | 1 |
F | Verde | Não Fumante | Doente | Solteiro(a) | 1 |
F | Preto | Fumante | Sadio | Solteiro(a) | 1 |
F | Castanho | Não Fumante | Doente | Casado(a) | 0 |
M | Azul | Fumante | Sadio | Solteiro(a) | 1 |
M | Castanho | Fumante | Sadio | Solteiro(a) | 1 |
M | Preto | Fumante | Sadio | Solteiro(a) | 1 |
Passo a passo para fazer gráficos GGPLOT2
Elementos de um gráfico utilizando ggplot
- Base de dados que será utilizada
- Aesthetic mapping (A parte estética do gráfico, eixos, cores, tamanhos, textos)
- Geometria que será utilizada (Tipo de gráfico)
- Escala (formato, unidade de medida)
- Rótulos, títulos legendas, etc..
Gráfico de Colunas ou barras verticais
=
grafico_coluna_geralggplot(variaveis_categoricas_nominais,aes(a_cor_olhos)) +
geom_bar(position = "dodge",fill="red") +
ggtitle("Número de alunos por cor dos olhos")+
xlab("Cor dos olhos") +
ylab("Frequência simples (Quantidade de alunos)")
ggplotly(grafico_coluna_geral)
Criando fatores e identificando seus níveis para ordenação
$a_cor_olhos_mod = factor(variaveis_categoricas_nominais$a_cor_olhos, levels =c("Verde","Castanho","Preto", "Azul")
variaveis_categoricas_nominais )
Gráfico de Colunas ou barras verticais frequências ordenadas
=
grafico_coluna_geralggplot(variaveis_categoricas_nominais,aes(a_cor_olhos_mod)) +
geom_bar(position = "dodge",fill="red") +
ggtitle("Número de alunos por cor dos olhos")+
xlab("Cor dos olhos") +
ylab("Frequência simples (Quantidade de alunos)")
ggplotly(grafico_coluna_geral)
Gráfico de Colunas ou barras verticais por sexo
=ggplot(variaveis_categoricas_nominais,aes(a_cor_olhos_mod,fill=a_sexo)) +
grafico_colunageom_bar(position = "dodge") +
ggtitle("Número de alunos por cor dos olhos e sexo")+
labs(fill="Sexo")+
xlab("Cor dos olhos") +
ylab("Frequência simples (Quantidade de alunos)")
ggplotly(grafico_coluna)
Gráfico de Colunas ou barras verticais (%)
=ggplot(variaveis_categoricas_nominais,aes(a_cor_olhos_mod,fill=a_sexo)) +
grafico_coluna_porcentgeom_bar(position = "dodge",aes(y = (..count..)/sum(..count..))) +
ggtitle("Número de alunos por cor dos olhos e sexo (%)")+
scale_y_continuous(labels=percent)+
labs(fill="Sexo")+
xlab("Cor dos olhos") +
ylab("Frequência simples (Quantidade de alunos)")
ggplotly(grafico_coluna_porcent)
## Warning: The dot-dot notation (`..count..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(count)` instead.
## ℹ The deprecated feature was likely used in the base package.
## Please report the issue to the authors.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
Gráfico de Colunas ou barras verticais empilhadas (%)
=ggplot(variaveis_categoricas_nominais,aes(a_cor_olhos_mod,fill=a_sexo)) +
grafico_colunas_empilhadasgeom_bar(position = 'fill') +
ggtitle("Número de alunos por cor dos olhos e sexo")+
scale_y_continuous(labels=percent) +
labs(fill="Sexo")+
xlab("Cor dos olhos") +
ylab("Frequência simples (Quantidade de alunos)")
ggplotly(grafico_colunas_empilhadas)
Gráfico de barras horizontais
=grafico_coluna + coord_flip()
grafico_barras_horizontais
ggplotly(grafico_barras_horizontais)
Gráfico de barras horizontais por Sexo
=grafico_coluna + coord_flip() + facet_grid(~a_sexo)
grafico_barras_horizontais_por_sexo
ggplotly(grafico_barras_horizontais_por_sexo)
Consolidando as análises
grid.arrange(grafico_coluna_geral,
grafico_coluna,
grafico_coluna_porcent,
grafico_barras_horizontais,
grafico_barras_horizontais_por_sexo,nrow=3,ncol=2) grafico_colunas_empilhadas,
Gráficos Estatísticos para variáveis Qualitativas - R
Criando o banco de dados
=c("A","B","C","D","E")
classe_social=c("Ensino fundamental","Ensino médio","Ensino Superior")
grau_instrucao=c("Estágio inicial","Estágio intermediário","Estágio terminal")
estagio_doenca=c("Janeiro","Fevereiro","março")
meses=c("Primeiro","Segundo","Terceiro")
ranking
=sample(classe_social,size=100, replace=TRUE)
a_classe_social=sample(grau_instrucao,size=100, replace=TRUE)
a_grau_intrucao=sample(estagio_doenca,size=100, replace=TRUE)
a_estagio_doenca=sample(meses,size=100, replace=TRUE)
a_meses=sample(ranking,size=100, replace=TRUE)
a_ranking
<<- data.frame(a_classe_social,
variaveis_categoricas_ordinais
a_grau_intrucao,
a_estagio_doenca,
a_meses,
a_ranking) variaveis_categoricas_ordinais
## a_classe_social a_grau_intrucao a_estagio_doenca a_meses
## 1 C Ensino Superior Estágio intermediário março
## 2 E Ensino fundamental Estágio intermediário Fevereiro
## 3 C Ensino fundamental Estágio intermediário Fevereiro
## 4 E Ensino Superior Estágio intermediário março
## 5 B Ensino médio Estágio terminal Fevereiro
## 6 C Ensino Superior Estágio inicial Janeiro
## 7 C Ensino Superior Estágio inicial Fevereiro
## 8 E Ensino Superior Estágio inicial Janeiro
## 9 A Ensino Superior Estágio inicial Fevereiro
## 10 A Ensino Superior Estágio terminal março
## 11 B Ensino médio Estágio terminal Fevereiro
## 12 C Ensino médio Estágio intermediário março
## 13 D Ensino fundamental Estágio intermediário março
## 14 A Ensino Superior Estágio inicial março
## 15 B Ensino médio Estágio inicial Fevereiro
## 16 B Ensino Superior Estágio inicial março
## 17 B Ensino fundamental Estágio inicial março
## 18 C Ensino Superior Estágio inicial Janeiro
## 19 A Ensino Superior Estágio inicial Fevereiro
## 20 D Ensino médio Estágio inicial março
## 21 A Ensino Superior Estágio intermediário Fevereiro
## 22 B Ensino fundamental Estágio terminal Fevereiro
## 23 C Ensino fundamental Estágio inicial março
## 24 A Ensino fundamental Estágio inicial março
## 25 E Ensino médio Estágio terminal Janeiro
## 26 C Ensino médio Estágio inicial Janeiro
## 27 C Ensino fundamental Estágio intermediário Janeiro
## 28 B Ensino médio Estágio inicial março
## 29 D Ensino médio Estágio intermediário Janeiro
## 30 B Ensino fundamental Estágio intermediário Janeiro
## 31 E Ensino fundamental Estágio inicial Janeiro
## 32 A Ensino médio Estágio terminal Fevereiro
## 33 D Ensino médio Estágio intermediário Fevereiro
## 34 C Ensino fundamental Estágio terminal março
## 35 B Ensino Superior Estágio intermediário Janeiro
## 36 C Ensino médio Estágio terminal março
## 37 B Ensino fundamental Estágio intermediário Janeiro
## 38 E Ensino fundamental Estágio terminal Fevereiro
## 39 A Ensino Superior Estágio intermediário março
## 40 E Ensino médio Estágio terminal Janeiro
## 41 A Ensino médio Estágio inicial Fevereiro
## 42 B Ensino fundamental Estágio intermediário Janeiro
## 43 C Ensino médio Estágio inicial Fevereiro
## 44 C Ensino Superior Estágio terminal Janeiro
## 45 D Ensino médio Estágio inicial Janeiro
## 46 C Ensino Superior Estágio intermediário Fevereiro
## 47 E Ensino Superior Estágio terminal março
## 48 D Ensino fundamental Estágio terminal Janeiro
## 49 B Ensino Superior Estágio terminal Fevereiro
## 50 A Ensino fundamental Estágio inicial Fevereiro
## 51 C Ensino fundamental Estágio inicial março
## 52 B Ensino fundamental Estágio intermediário Janeiro
## 53 B Ensino médio Estágio inicial Fevereiro
## 54 A Ensino fundamental Estágio inicial Janeiro
## 55 A Ensino Superior Estágio intermediário março
## 56 B Ensino fundamental Estágio terminal Fevereiro
## 57 A Ensino fundamental Estágio inicial Fevereiro
## 58 C Ensino médio Estágio terminal março
## 59 C Ensino médio Estágio terminal março
## 60 E Ensino médio Estágio terminal Fevereiro
## 61 E Ensino Superior Estágio terminal Fevereiro
## 62 A Ensino Superior Estágio inicial março
## 63 D Ensino Superior Estágio intermediário março
## 64 D Ensino Superior Estágio terminal Janeiro
## 65 D Ensino fundamental Estágio inicial março
## 66 E Ensino médio Estágio terminal março
## 67 D Ensino fundamental Estágio inicial março
## 68 E Ensino Superior Estágio inicial Janeiro
## 69 A Ensino fundamental Estágio inicial março
## 70 A Ensino médio Estágio intermediário Janeiro
## 71 C Ensino médio Estágio terminal Fevereiro
## 72 B Ensino fundamental Estágio inicial março
## 73 B Ensino Superior Estágio inicial março
## 74 C Ensino fundamental Estágio inicial Janeiro
## 75 B Ensino Superior Estágio terminal Janeiro
## 76 C Ensino Superior Estágio terminal março
## 77 A Ensino médio Estágio intermediário março
## 78 B Ensino fundamental Estágio intermediário março
## 79 B Ensino fundamental Estágio intermediário Janeiro
## 80 D Ensino médio Estágio intermediário março
## 81 D Ensino Superior Estágio terminal março
## 82 E Ensino médio Estágio terminal Fevereiro
## 83 C Ensino médio Estágio intermediário março
## 84 A Ensino fundamental Estágio inicial Fevereiro
## 85 B Ensino fundamental Estágio inicial Fevereiro
## 86 C Ensino fundamental Estágio intermediário março
## 87 D Ensino fundamental Estágio intermediário Fevereiro
## 88 B Ensino médio Estágio intermediário Janeiro
## 89 C Ensino médio Estágio intermediário Janeiro
## 90 A Ensino fundamental Estágio inicial março
## 91 A Ensino fundamental Estágio inicial Janeiro
## 92 C Ensino fundamental Estágio terminal Fevereiro
## 93 B Ensino Superior Estágio intermediário março
## 94 E Ensino Superior Estágio inicial Fevereiro
## 95 A Ensino Superior Estágio terminal Fevereiro
## 96 C Ensino médio Estágio inicial Fevereiro
## 97 C Ensino médio Estágio intermediário Janeiro
## 98 D Ensino fundamental Estágio intermediário março
## 99 D Ensino Superior Estágio terminal Janeiro
## 100 E Ensino Superior Estágio terminal Janeiro
## a_ranking
## 1 Segundo
## 2 Segundo
## 3 Primeiro
## 4 Primeiro
## 5 Segundo
## 6 Terceiro
## 7 Segundo
## 8 Terceiro
## 9 Primeiro
## 10 Terceiro
## 11 Segundo
## 12 Segundo
## 13 Primeiro
## 14 Segundo
## 15 Segundo
## 16 Terceiro
## 17 Terceiro
## 18 Primeiro
## 19 Primeiro
## 20 Primeiro
## 21 Terceiro
## 22 Primeiro
## 23 Segundo
## 24 Segundo
## 25 Segundo
## 26 Terceiro
## 27 Segundo
## 28 Segundo
## 29 Primeiro
## 30 Terceiro
## 31 Primeiro
## 32 Primeiro
## 33 Terceiro
## 34 Segundo
## 35 Primeiro
## 36 Terceiro
## 37 Segundo
## 38 Terceiro
## 39 Primeiro
## 40 Segundo
## 41 Segundo
## 42 Terceiro
## 43 Primeiro
## 44 Terceiro
## 45 Segundo
## 46 Segundo
## 47 Terceiro
## 48 Segundo
## 49 Primeiro
## 50 Terceiro
## 51 Segundo
## 52 Primeiro
## 53 Segundo
## 54 Segundo
## 55 Primeiro
## 56 Primeiro
## 57 Terceiro
## 58 Segundo
## 59 Terceiro
## 60 Terceiro
## 61 Terceiro
## 62 Primeiro
## 63 Primeiro
## 64 Terceiro
## 65 Primeiro
## 66 Primeiro
## 67 Primeiro
## 68 Primeiro
## 69 Segundo
## 70 Segundo
## 71 Primeiro
## 72 Segundo
## 73 Primeiro
## 74 Segundo
## 75 Primeiro
## 76 Primeiro
## 77 Terceiro
## 78 Terceiro
## 79 Primeiro
## 80 Segundo
## 81 Primeiro
## 82 Terceiro
## 83 Terceiro
## 84 Segundo
## 85 Segundo
## 86 Segundo
## 87 Segundo
## 88 Primeiro
## 89 Primeiro
## 90 Segundo
## 91 Primeiro
## 92 Primeiro
## 93 Segundo
## 94 Segundo
## 95 Segundo
## 96 Segundo
## 97 Terceiro
## 98 Segundo
## 99 Segundo
## 100 Terceiro
%>% kbl %>% kable_material_dark(full_width = F) variaveis_categoricas_ordinais
a_classe_social | a_grau_intrucao | a_estagio_doenca | a_meses | a_ranking |
---|---|---|---|---|
C | Ensino Superior | Estágio intermediário | março | Segundo |
E | Ensino fundamental | Estágio intermediário | Fevereiro | Segundo |
C | Ensino fundamental | Estágio intermediário | Fevereiro | Primeiro |
E | Ensino Superior | Estágio intermediário | março | Primeiro |
B | Ensino médio | Estágio terminal | Fevereiro | Segundo |
C | Ensino Superior | Estágio inicial | Janeiro | Terceiro |
C | Ensino Superior | Estágio inicial | Fevereiro | Segundo |
E | Ensino Superior | Estágio inicial | Janeiro | Terceiro |
A | Ensino Superior | Estágio inicial | Fevereiro | Primeiro |
A | Ensino Superior | Estágio terminal | março | Terceiro |
B | Ensino médio | Estágio terminal | Fevereiro | Segundo |
C | Ensino médio | Estágio intermediário | março | Segundo |
D | Ensino fundamental | Estágio intermediário | março | Primeiro |
A | Ensino Superior | Estágio inicial | março | Segundo |
B | Ensino médio | Estágio inicial | Fevereiro | Segundo |
B | Ensino Superior | Estágio inicial | março | Terceiro |
B | Ensino fundamental | Estágio inicial | março | Terceiro |
C | Ensino Superior | Estágio inicial | Janeiro | Primeiro |
A | Ensino Superior | Estágio inicial | Fevereiro | Primeiro |
D | Ensino médio | Estágio inicial | março | Primeiro |
A | Ensino Superior | Estágio intermediário | Fevereiro | Terceiro |
B | Ensino fundamental | Estágio terminal | Fevereiro | Primeiro |
C | Ensino fundamental | Estágio inicial | março | Segundo |
A | Ensino fundamental | Estágio inicial | março | Segundo |
E | Ensino médio | Estágio terminal | Janeiro | Segundo |
C | Ensino médio | Estágio inicial | Janeiro | Terceiro |
C | Ensino fundamental | Estágio intermediário | Janeiro | Segundo |
B | Ensino médio | Estágio inicial | março | Segundo |
D | Ensino médio | Estágio intermediário | Janeiro | Primeiro |
B | Ensino fundamental | Estágio intermediário | Janeiro | Terceiro |
E | Ensino fundamental | Estágio inicial | Janeiro | Primeiro |
A | Ensino médio | Estágio terminal | Fevereiro | Primeiro |
D | Ensino médio | Estágio intermediário | Fevereiro | Terceiro |
C | Ensino fundamental | Estágio terminal | março | Segundo |
B | Ensino Superior | Estágio intermediário | Janeiro | Primeiro |
C | Ensino médio | Estágio terminal | março | Terceiro |
B | Ensino fundamental | Estágio intermediário | Janeiro | Segundo |
E | Ensino fundamental | Estágio terminal | Fevereiro | Terceiro |
A | Ensino Superior | Estágio intermediário | março | Primeiro |
E | Ensino médio | Estágio terminal | Janeiro | Segundo |
A | Ensino médio | Estágio inicial | Fevereiro | Segundo |
B | Ensino fundamental | Estágio intermediário | Janeiro | Terceiro |
C | Ensino médio | Estágio inicial | Fevereiro | Primeiro |
C | Ensino Superior | Estágio terminal | Janeiro | Terceiro |
D | Ensino médio | Estágio inicial | Janeiro | Segundo |
C | Ensino Superior | Estágio intermediário | Fevereiro | Segundo |
E | Ensino Superior | Estágio terminal | março | Terceiro |
D | Ensino fundamental | Estágio terminal | Janeiro | Segundo |
B | Ensino Superior | Estágio terminal | Fevereiro | Primeiro |
A | Ensino fundamental | Estágio inicial | Fevereiro | Terceiro |
C | Ensino fundamental | Estágio inicial | março | Segundo |
B | Ensino fundamental | Estágio intermediário | Janeiro | Primeiro |
B | Ensino médio | Estágio inicial | Fevereiro | Segundo |
A | Ensino fundamental | Estágio inicial | Janeiro | Segundo |
A | Ensino Superior | Estágio intermediário | março | Primeiro |
B | Ensino fundamental | Estágio terminal | Fevereiro | Primeiro |
A | Ensino fundamental | Estágio inicial | Fevereiro | Terceiro |
C | Ensino médio | Estágio terminal | março | Segundo |
C | Ensino médio | Estágio terminal | março | Terceiro |
E | Ensino médio | Estágio terminal | Fevereiro | Terceiro |
E | Ensino Superior | Estágio terminal | Fevereiro | Terceiro |
A | Ensino Superior | Estágio inicial | março | Primeiro |
D | Ensino Superior | Estágio intermediário | março | Primeiro |
D | Ensino Superior | Estágio terminal | Janeiro | Terceiro |
D | Ensino fundamental | Estágio inicial | março | Primeiro |
E | Ensino médio | Estágio terminal | março | Primeiro |
D | Ensino fundamental | Estágio inicial | março | Primeiro |
E | Ensino Superior | Estágio inicial | Janeiro | Primeiro |
A | Ensino fundamental | Estágio inicial | março | Segundo |
A | Ensino médio | Estágio intermediário | Janeiro | Segundo |
C | Ensino médio | Estágio terminal | Fevereiro | Primeiro |
B | Ensino fundamental | Estágio inicial | março | Segundo |
B | Ensino Superior | Estágio inicial | março | Primeiro |
C | Ensino fundamental | Estágio inicial | Janeiro | Segundo |
B | Ensino Superior | Estágio terminal | Janeiro | Primeiro |
C | Ensino Superior | Estágio terminal | março | Primeiro |
A | Ensino médio | Estágio intermediário | março | Terceiro |
B | Ensino fundamental | Estágio intermediário | março | Terceiro |
B | Ensino fundamental | Estágio intermediário | Janeiro | Primeiro |
D | Ensino médio | Estágio intermediário | março | Segundo |
D | Ensino Superior | Estágio terminal | março | Primeiro |
E | Ensino médio | Estágio terminal | Fevereiro | Terceiro |
C | Ensino médio | Estágio intermediário | março | Terceiro |
A | Ensino fundamental | Estágio inicial | Fevereiro | Segundo |
B | Ensino fundamental | Estágio inicial | Fevereiro | Segundo |
C | Ensino fundamental | Estágio intermediário | março | Segundo |
D | Ensino fundamental | Estágio intermediário | Fevereiro | Segundo |
B | Ensino médio | Estágio intermediário | Janeiro | Primeiro |
C | Ensino médio | Estágio intermediário | Janeiro | Primeiro |
A | Ensino fundamental | Estágio inicial | março | Segundo |
A | Ensino fundamental | Estágio inicial | Janeiro | Primeiro |
C | Ensino fundamental | Estágio terminal | Fevereiro | Primeiro |
B | Ensino Superior | Estágio intermediário | março | Segundo |
E | Ensino Superior | Estágio inicial | Fevereiro | Segundo |
A | Ensino Superior | Estágio terminal | Fevereiro | Segundo |
C | Ensino médio | Estágio inicial | Fevereiro | Segundo |
C | Ensino médio | Estágio intermediário | Janeiro | Terceiro |
D | Ensino fundamental | Estágio intermediário | março | Segundo |
D | Ensino Superior | Estágio terminal | Janeiro | Segundo |
E | Ensino Superior | Estágio terminal | Janeiro | Terceiro |
Pizza frequência simples (Base do R)
Criando a tabela de frequências para fazer a pizza
=table(variaveis_categoricas_ordinais$a_classe_social)
df_pizza_tab<<- data.frame(df_pizza_tab)
df_pizza %>% kbl %>% kable_material_dark(full_width = F) df_pizza
Var1 | Freq |
---|---|
A | 21 |
B | 23 |
C | 26 |
D | 15 |
E | 15 |
Criando a pizza frequência absoluta na base do R
pie(df_pizza$Freq,
labels=paste(df_pizza$Var1,df_pizza$Freq),
main="Gráfico de pizza do número de pessoas por classe social")
Pizza frequência relativa na base do R (%)
=prop.table(df_pizza_tab)
df_pizza_porcent<<- as.data.frame(df_pizza_porcent)
df_pizza_porcent df_pizza_porcent
## Var1 Freq
## 1 A 0.21
## 2 B 0.23
## 3 C 0.26
## 4 D 0.15
## 5 E 0.15
#Criando a coluna qualquer_nome com label % usando base
$qualquer_nome=paste(df_pizza_porcent$Freq*100,"%")
df_pizza_porcent df_pizza_porcent
## Var1 Freq qualquer_nome
## 1 A 0.21 21 %
## 2 B 0.23 23 %
## 3 C 0.26 26 %
## 4 D 0.15 15 %
## 5 E 0.15 15 %
#Criando a coluna frequencia com label % usando o dplyr
= df_pizza_porcent %>% mutate( frequencia=paste(df_pizza_porcent$Freq*100,"%"))
df_pizza_porcent
#Criando a pizza
pie(df_pizza_porcent$Freq,
labels=df_pizza_porcent$frequencia,
main="Gráfico de pizza - Frequência relativa classe social (%)")
Criando a pizza interativa com o pacote plotly
= plot_ly(df_pizza,
grafico_pizza_iterativo labels = ~Var1,
values = ~Freq,
type = 'pie') %>%
layout(title = 'Frequência relativa da Classe Social (%) ')
grafico_pizza_iterativo
Passo a passo para fazer gráficos GGPLOT2
Elementos de um gráfico utilizando ggplot
- Base de dados que será utilizada
- Aesthetic mapping (A parte estética do gráfico, eixos, cores, tamanhos, textos)
- Geometria que será utilizada (Tipo de gráfico)
- Escala (formato, unidade de medida)
- Rótulos, títulos legendas, etc..
Gráfico de Colunas ou barras verticais
=ggplot(variaveis_categoricas_ordinais,aes(x=a_classe_social)) +
grafico_colunageom_bar(position = "dodge") +
ggtitle("Número de pessoas por classe social")+
xlab("Classe social") +
ylab("Número de pessoas (Frequência simples)")
ggplotly(grafico_coluna)
Gráfico de Colunas ou barras verticais com frequência relativa
=ggplot(variaveis_categoricas_ordinais,aes(x=a_classe_social)) +
grafico_coluna_porcentgeom_bar(aes(y = (..count..)/sum(..count..))) +
ggtitle("Número de pessoas por classe social") +
scale_y_continuous(labels=percent) +
xlab("Classe social") +
ylab("Proporção de pessoas % (Frequência Relativa)")
ggplotly(grafico_coluna_porcent)
Gráfico de Colunas ou barras verticais empilhadas com frequência relativa e grau de instrução
=ggplot(variaveis_categoricas_ordinais,aes(x=a_classe_social,fill=a_grau_intrucao)) +
grafico_coluna_empilhadageom_bar(position = 'fill',show.legend = FALSE) +
ggtitle("Número de pessoas por classe social")+
scale_y_continuous(labels=percent) +
xlab("Classe social") +
ylab("Proporção de pessoas % (Frequência Relativa)")
ggplotly(grafico_coluna_empilhada)
Gráfico de Colunas ou barras verticais com frequência relativa por grau de instrução
=ggplot(variaveis_categoricas_ordinais,aes(x=a_classe_social,fill=a_grau_intrucao)) +
grafico_coluna_porcent_por_grau_instrucaogeom_bar(aes(y = (..count..)/sum(..count..)),show.legend = FALSE) +
ggtitle("Número de pessoas por classe social") +
scale_y_continuous(labels=percent) +
xlab("Classe social") +
ylab("Número de pessoas (Frequência simples)") +
facet_grid(~a_grau_intrucao)
ggplotly(grafico_coluna_porcent_por_grau_instrucao)
Consolidando as análises ggplot
grid.arrange(grafico_coluna,
grafico_coluna_porcent,
grafico_coluna_porcent_por_grau_instrucao,
grafico_coluna_empilhada, nrow=2,ncol=2)
Consolidando as análises plotly
::subplot(ggplotly(grafico_coluna),
plotlyggplotly(grafico_coluna_porcent),
ggplotly(grafico_coluna_porcent_por_grau_instrucao),
ggplotly(grafico_coluna_empilhada),
nrows = 4)
Gráficos Estatísticos para variáveis Quantitativas - R
Banco Iris
<<- iris
dados %>% kbl %>% kable_material_dark(full_width = F) dados
Sepal.Length | Sepal.Width | Petal.Length | Petal.Width | Species |
---|---|---|---|---|
5.1 | 3.5 | 1.4 | 0.2 | setosa |
4.9 | 3.0 | 1.4 | 0.2 | setosa |
4.7 | 3.2 | 1.3 | 0.2 | setosa |
4.6 | 3.1 | 1.5 | 0.2 | setosa |
5.0 | 3.6 | 1.4 | 0.2 | setosa |
5.4 | 3.9 | 1.7 | 0.4 | setosa |
4.6 | 3.4 | 1.4 | 0.3 | setosa |
5.0 | 3.4 | 1.5 | 0.2 | setosa |
4.4 | 2.9 | 1.4 | 0.2 | setosa |
4.9 | 3.1 | 1.5 | 0.1 | setosa |
5.4 | 3.7 | 1.5 | 0.2 | setosa |
4.8 | 3.4 | 1.6 | 0.2 | setosa |
4.8 | 3.0 | 1.4 | 0.1 | setosa |
4.3 | 3.0 | 1.1 | 0.1 | setosa |
5.8 | 4.0 | 1.2 | 0.2 | setosa |
5.7 | 4.4 | 1.5 | 0.4 | setosa |
5.4 | 3.9 | 1.3 | 0.4 | setosa |
5.1 | 3.5 | 1.4 | 0.3 | setosa |
5.7 | 3.8 | 1.7 | 0.3 | setosa |
5.1 | 3.8 | 1.5 | 0.3 | setosa |
5.4 | 3.4 | 1.7 | 0.2 | setosa |
5.1 | 3.7 | 1.5 | 0.4 | setosa |
4.6 | 3.6 | 1.0 | 0.2 | setosa |
5.1 | 3.3 | 1.7 | 0.5 | setosa |
4.8 | 3.4 | 1.9 | 0.2 | setosa |
5.0 | 3.0 | 1.6 | 0.2 | setosa |
5.0 | 3.4 | 1.6 | 0.4 | setosa |
5.2 | 3.5 | 1.5 | 0.2 | setosa |
5.2 | 3.4 | 1.4 | 0.2 | setosa |
4.7 | 3.2 | 1.6 | 0.2 | setosa |
4.8 | 3.1 | 1.6 | 0.2 | setosa |
5.4 | 3.4 | 1.5 | 0.4 | setosa |
5.2 | 4.1 | 1.5 | 0.1 | setosa |
5.5 | 4.2 | 1.4 | 0.2 | setosa |
4.9 | 3.1 | 1.5 | 0.2 | setosa |
5.0 | 3.2 | 1.2 | 0.2 | setosa |
5.5 | 3.5 | 1.3 | 0.2 | setosa |
4.9 | 3.6 | 1.4 | 0.1 | setosa |
4.4 | 3.0 | 1.3 | 0.2 | setosa |
5.1 | 3.4 | 1.5 | 0.2 | setosa |
5.0 | 3.5 | 1.3 | 0.3 | setosa |
4.5 | 2.3 | 1.3 | 0.3 | setosa |
4.4 | 3.2 | 1.3 | 0.2 | setosa |
5.0 | 3.5 | 1.6 | 0.6 | setosa |
5.1 | 3.8 | 1.9 | 0.4 | setosa |
4.8 | 3.0 | 1.4 | 0.3 | setosa |
5.1 | 3.8 | 1.6 | 0.2 | setosa |
4.6 | 3.2 | 1.4 | 0.2 | setosa |
5.3 | 3.7 | 1.5 | 0.2 | setosa |
5.0 | 3.3 | 1.4 | 0.2 | setosa |
7.0 | 3.2 | 4.7 | 1.4 | versicolor |
6.4 | 3.2 | 4.5 | 1.5 | versicolor |
6.9 | 3.1 | 4.9 | 1.5 | versicolor |
5.5 | 2.3 | 4.0 | 1.3 | versicolor |
6.5 | 2.8 | 4.6 | 1.5 | versicolor |
5.7 | 2.8 | 4.5 | 1.3 | versicolor |
6.3 | 3.3 | 4.7 | 1.6 | versicolor |
4.9 | 2.4 | 3.3 | 1.0 | versicolor |
6.6 | 2.9 | 4.6 | 1.3 | versicolor |
5.2 | 2.7 | 3.9 | 1.4 | versicolor |
5.0 | 2.0 | 3.5 | 1.0 | versicolor |
5.9 | 3.0 | 4.2 | 1.5 | versicolor |
6.0 | 2.2 | 4.0 | 1.0 | versicolor |
6.1 | 2.9 | 4.7 | 1.4 | versicolor |
5.6 | 2.9 | 3.6 | 1.3 | versicolor |
6.7 | 3.1 | 4.4 | 1.4 | versicolor |
5.6 | 3.0 | 4.5 | 1.5 | versicolor |
5.8 | 2.7 | 4.1 | 1.0 | versicolor |
6.2 | 2.2 | 4.5 | 1.5 | versicolor |
5.6 | 2.5 | 3.9 | 1.1 | versicolor |
5.9 | 3.2 | 4.8 | 1.8 | versicolor |
6.1 | 2.8 | 4.0 | 1.3 | versicolor |
6.3 | 2.5 | 4.9 | 1.5 | versicolor |
6.1 | 2.8 | 4.7 | 1.2 | versicolor |
6.4 | 2.9 | 4.3 | 1.3 | versicolor |
6.6 | 3.0 | 4.4 | 1.4 | versicolor |
6.8 | 2.8 | 4.8 | 1.4 | versicolor |
6.7 | 3.0 | 5.0 | 1.7 | versicolor |
6.0 | 2.9 | 4.5 | 1.5 | versicolor |
5.7 | 2.6 | 3.5 | 1.0 | versicolor |
5.5 | 2.4 | 3.8 | 1.1 | versicolor |
5.5 | 2.4 | 3.7 | 1.0 | versicolor |
5.8 | 2.7 | 3.9 | 1.2 | versicolor |
6.0 | 2.7 | 5.1 | 1.6 | versicolor |
5.4 | 3.0 | 4.5 | 1.5 | versicolor |
6.0 | 3.4 | 4.5 | 1.6 | versicolor |
6.7 | 3.1 | 4.7 | 1.5 | versicolor |
6.3 | 2.3 | 4.4 | 1.3 | versicolor |
5.6 | 3.0 | 4.1 | 1.3 | versicolor |
5.5 | 2.5 | 4.0 | 1.3 | versicolor |
5.5 | 2.6 | 4.4 | 1.2 | versicolor |
6.1 | 3.0 | 4.6 | 1.4 | versicolor |
5.8 | 2.6 | 4.0 | 1.2 | versicolor |
5.0 | 2.3 | 3.3 | 1.0 | versicolor |
5.6 | 2.7 | 4.2 | 1.3 | versicolor |
5.7 | 3.0 | 4.2 | 1.2 | versicolor |
5.7 | 2.9 | 4.2 | 1.3 | versicolor |
6.2 | 2.9 | 4.3 | 1.3 | versicolor |
5.1 | 2.5 | 3.0 | 1.1 | versicolor |
5.7 | 2.8 | 4.1 | 1.3 | versicolor |
6.3 | 3.3 | 6.0 | 2.5 | virginica |
5.8 | 2.7 | 5.1 | 1.9 | virginica |
7.1 | 3.0 | 5.9 | 2.1 | virginica |
6.3 | 2.9 | 5.6 | 1.8 | virginica |
6.5 | 3.0 | 5.8 | 2.2 | virginica |
7.6 | 3.0 | 6.6 | 2.1 | virginica |
4.9 | 2.5 | 4.5 | 1.7 | virginica |
7.3 | 2.9 | 6.3 | 1.8 | virginica |
6.7 | 2.5 | 5.8 | 1.8 | virginica |
7.2 | 3.6 | 6.1 | 2.5 | virginica |
6.5 | 3.2 | 5.1 | 2.0 | virginica |
6.4 | 2.7 | 5.3 | 1.9 | virginica |
6.8 | 3.0 | 5.5 | 2.1 | virginica |
5.7 | 2.5 | 5.0 | 2.0 | virginica |
5.8 | 2.8 | 5.1 | 2.4 | virginica |
6.4 | 3.2 | 5.3 | 2.3 | virginica |
6.5 | 3.0 | 5.5 | 1.8 | virginica |
7.7 | 3.8 | 6.7 | 2.2 | virginica |
7.7 | 2.6 | 6.9 | 2.3 | virginica |
6.0 | 2.2 | 5.0 | 1.5 | virginica |
6.9 | 3.2 | 5.7 | 2.3 | virginica |
5.6 | 2.8 | 4.9 | 2.0 | virginica |
7.7 | 2.8 | 6.7 | 2.0 | virginica |
6.3 | 2.7 | 4.9 | 1.8 | virginica |
6.7 | 3.3 | 5.7 | 2.1 | virginica |
7.2 | 3.2 | 6.0 | 1.8 | virginica |
6.2 | 2.8 | 4.8 | 1.8 | virginica |
6.1 | 3.0 | 4.9 | 1.8 | virginica |
6.4 | 2.8 | 5.6 | 2.1 | virginica |
7.2 | 3.0 | 5.8 | 1.6 | virginica |
7.4 | 2.8 | 6.1 | 1.9 | virginica |
7.9 | 3.8 | 6.4 | 2.0 | virginica |
6.4 | 2.8 | 5.6 | 2.2 | virginica |
6.3 | 2.8 | 5.1 | 1.5 | virginica |
6.1 | 2.6 | 5.6 | 1.4 | virginica |
7.7 | 3.0 | 6.1 | 2.3 | virginica |
6.3 | 3.4 | 5.6 | 2.4 | virginica |
6.4 | 3.1 | 5.5 | 1.8 | virginica |
6.0 | 3.0 | 4.8 | 1.8 | virginica |
6.9 | 3.1 | 5.4 | 2.1 | virginica |
6.7 | 3.1 | 5.6 | 2.4 | virginica |
6.9 | 3.1 | 5.1 | 2.3 | virginica |
5.8 | 2.7 | 5.1 | 1.9 | virginica |
6.8 | 3.2 | 5.9 | 2.3 | virginica |
6.7 | 3.3 | 5.7 | 2.5 | virginica |
6.7 | 3.0 | 5.2 | 2.3 | virginica |
6.3 | 2.5 | 5.0 | 1.9 | virginica |
6.5 | 3.0 | 5.2 | 2.0 | virginica |
6.2 | 3.4 | 5.4 | 2.3 | virginica |
5.9 | 3.0 | 5.1 | 1.8 | virginica |
Gráfico histograma do tamanho da Sépala das Plantas
= ggplot(dados,aes(x=Sepal.Length)) +
grafico_hist geom_histogram(color = "black",fill="lightblue",bins =30)+
ggtitle("Gráfico histograma do tamanho da Sépala das Plantas")+
xlab("Tamanho das Sépalas") +
ylab("Frequência simples") +
theme()
grafico_hist
ggplotly(grafico_hist)
Gráfico de Box-plot do tamanho da Sépala vs o tamanho das Pétalas das Plantas
= ggplot(dados, aes(x=Sepal.Length, y=Petal.Length,fill=Species)) +
grafico_boxplot geom_boxplot()+
ggtitle("Gráfico de Box-plot do tamanho da Sépala vs o tamanho das Pétalas das Plantas")+
xlab("Tamanho das Sépalas") +
ylab("Tamanho das Pétalas")
grafico_boxplot
Gráfico de Dispersão do tamanho da Sépala vs o tamanho das Pétalas das Plantas
= ggplot(dados, aes(x=Sepal.Length, y=Petal.Length,col=Species)) +
grafico_dispersao_cor geom_point(size=4)+
ggtitle("Gráfico de Dispersão do tamanho da Sépala vs o tamanho das Pétalas das Plantas")+
xlab("Tamanho das Sépalas") +
ylab("Tamanho das Pétalas")
grafico_dispersao_cor
ggplotly(grafico_dispersao_cor)
Gráfico de Dispersão por Spécie com pontos proporcionais ao tamanho das sépalas
= ggplot(dados, aes(x=Sepal.Length, y=Petal.Length,col=Species)) +
grafico_dispersao_tamanho geom_point(aes(size=Sepal.Length))+
ggtitle("Gráfico de Dispersão do tamanho da Sépala vs o tamanho das Pétalas das Plantas")+
xlab("Tamanho das Sépalas") +
ylab("Tamanho das Pétalas")
grafico_dispersao_tamanho
Gráfico de Dispersão - facetas por espécie
= ggplot(dados, aes(x=Sepal.Length, y=Petal.Length,col=Species)) +
grafico_dispersao_especie geom_point(size=4)+
ggtitle("Gráfico de Dispersão do tamanho da Sépala vs o tamanho das Pétalas das Plantas")+
xlab("Tamanho das Sépalas") +
ylab("Tamanho das Pétalas") +
facet_wrap(~Species)
grafico_dispersao_especie
ggplotly(grafico_dispersao_especie)
Gráfico de linhas do desemprego nos Estados Unidos de 1967 a 2015 - Economics
<<- economics
dados2 =ggplot(dados2, aes(x=date, y=unemploy)) +
grafico_linhasgeom_line(col="red") +
xlab("Ano") +
ylab("Desemprego (em milhares)") +
ggtitle("Desemprego nos Estados Unidos de 1967 a 2015 - Economics")
grafico_linhas
ggplotly(grafico_linhas)
Consolidando as análises ggplot2
grid.arrange(
grafico_hist,
grafico_boxplot,
grafico_dispersao_cor,
grafico_dispersao_tamanho,
grafico_dispersao_especie,
grafico_linhas,nrow=3,ncol=2)
Gráfico de linhas - colocando constantes nas linhas horizontais
=ggplot(economics, aes(x=date, y=unemploy)) +
grafico_linhasgeom_line(col="red") +
geom_hline(yintercept = c(6000,10000))+
xlab("Ano") +
ylab("Desemprego (em milhares)") +
ggtitle("Desemprego nos Estados Unidos de 1967 a 2015 - Economics")
grafico_linhas
ggplotly(grafico_linhas)
Criando estados fictícios
= dados2 %>% mutate( estados=case_when(unemploy > mean(unemploy) ~ "estado_acima_da_media",
dados2 <= mean(unemploy) ~ "estado_abaixo_ou_igual_a_media")
unemploy )
Quantos acima e quantos abaixo da média?
table(dados2$estados) %>% kbl %>% kable_material_dark(full_width = F)
Var1 | Freq |
---|---|
estado_abaixo_ou_igual_a_media | 313 |
estado_acima_da_media | 261 |
Criando quartis
=quantile(dados2$unemploy,0.25)
q1=quantile(dados2$unemploy,0.75)
q3cbind(q1,q3)
## q1 q3
## 25% 6284 8685.5
Gráfico de linhas - colocando os quartis nas linhas horizontais
=ggplot(dados2, aes(x=date, y=unemploy)) +
grafico_linhasgeom_line(col="red") +
geom_hline(yintercept = c(q1[[1]],q3[[1]]))+
#geom_vline(xintercept = median(dados2$date))+
xlab("Ano") +
ylab("Desemprego (em milhares)") +
ggtitle("Desemprego nos Estados Unidos de 1967 a 2015 - Economics") +
facet_grid(~estados)
grafico_linhas
ggplotly(grafico_linhas)
Criando limites inferiores e superiores (3 Sigma)
=mean(dados2$unemploy)-3*sd(dados2$unemploy)
l1
=mean(dados2$unemploy)+3*sd(dados2$unemploy) l2
Gráfico de linhas - colocando os limites com médias e desvios nas linhas horizontais
=ggplot(dados2, aes(x=date, y=unemploy)) +
grafico_linhasgeom_line(col="red") +
geom_hline(yintercept = c(l1,l2))+
#geom_vline(xintercept = median(dados2$date))+
xlab("Ano") +
ylab("Desemprego (em milhares)") +
ggtitle("Desemprego nos Estados Unidos de 1967 a 2015 - Economics") +
facet_grid(~estados)
grafico_linhas
ggplotly(grafico_linhas)
Gráfico de histograma do desemprego nos Estados Unidos de 1967 a 2015 - Economics
= ggplot(dados2,aes(x=unemploy)) +
grafico_hist geom_histogram(color = "black",fill="lightblue",bins=30)+
ggtitle("Gráfico histograma do desemprego nos Estados Unidos de 1967 a 2015 - Economics")+
xlab("Quantidade de") +
ylab("Frequência simples") +
theme()
grafico_hist
ggplotly(grafico_hist)
Verificando a normalidade pelo teste de Shapiro wilk
shapiro.test(dados2$unemploy)
##
## Shapiro-Wilk normality test
##
## data: dados2$unemploy
## W = 0.94639, p-value = 1.473e-13
Criando categorias em classes
=min(dados2$unemploy)
minimo
=quantile(dados2$unemploy,0.5)
q2
=quantile(dados2$unemploy,0.75)
q3
=max(dados2$unemploy)
maximo
$unemploy_classes=
dados2cut(dados2$unemploy, breaks = c(minimo,q2,q3,maximo),
labels = c("min -|Q2", "Q2-|Q3", "Q3-|max"),
include.lowest = F)
Contabilizando as frequências por classe na Pizza
=table(dados2$unemploy_classes)
df_pizza_tab<<- data.frame(df_pizza_tab)
df_pizza
= plot_ly(df_pizza,
grafico_pizza_iterativo labels = ~Var1,
values = ~Freq,
type = 'pie') %>%
layout(title = 'Frequência relativa da Classe Social (%) ')
grafico_pizza_iterativo
Instalando e carregando bibliotecas adicionais
=c(
vetor_pacotes"treemap", #habilita gráficos treemap e mapas de calor
"RColorBrewer", #habilita trabalhar com cores mais profissionais,
"wordcloud", #habilita nuvens de palavras
"esquisse" , #transforma o R em um tableau para gráficos
"rgl" , #habilita grafos 3d
"igraph" #pacote mais geral para grafos no R
)#install.packages(vetor_pacotes)
lapply(vetor_pacotes,
require, character.only = TRUE)
## Carregando pacotes exigidos: treemap
## Carregando pacotes exigidos: RColorBrewer
## Carregando pacotes exigidos: wordcloud
## Carregando pacotes exigidos: esquisse
## Carregando pacotes exigidos: rgl
## Carregando pacotes exigidos: igraph
##
## Attaching package: 'igraph'
## The following object is masked from 'package:plotly':
##
## groups
## The following object is masked from 'package:DescTools':
##
## %c%
## The following objects are masked from 'package:lubridate':
##
## %--%, union
## The following objects are masked from 'package:dplyr':
##
## as_data_frame, groups, union
## The following objects are masked from 'package:purrr':
##
## compose, simplify
## The following object is masked from 'package:tidyr':
##
## crossing
## The following object is masked from 'package:tibble':
##
## as_data_frame
## The following objects are masked from 'package:stats':
##
## decompose, spectrum
## The following object is masked from 'package:base':
##
## union
## [[1]]
## [1] TRUE
##
## [[2]]
## [1] TRUE
##
## [[3]]
## [1] TRUE
##
## [[4]]
## [1] TRUE
##
## [[5]]
## [1] TRUE
##
## [[6]]
## [1] TRUE
Banco mtcars
<<- mtcars
dados %>% kbl %>% kable_material_dark(full_width = F) dados
mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb | |
---|---|---|---|---|---|---|---|---|---|---|---|
Mazda RX4 | 21.0 | 6 | 160.0 | 110 | 3.90 | 2.620 | 16.46 | 0 | 1 | 4 | 4 |
Mazda RX4 Wag | 21.0 | 6 | 160.0 | 110 | 3.90 | 2.875 | 17.02 | 0 | 1 | 4 | 4 |
Datsun 710 | 22.8 | 4 | 108.0 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1 |
Hornet 4 Drive | 21.4 | 6 | 258.0 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1 |
Hornet Sportabout | 18.7 | 8 | 360.0 | 175 | 3.15 | 3.440 | 17.02 | 0 | 0 | 3 | 2 |
Valiant | 18.1 | 6 | 225.0 | 105 | 2.76 | 3.460 | 20.22 | 1 | 0 | 3 | 1 |
Duster 360 | 14.3 | 8 | 360.0 | 245 | 3.21 | 3.570 | 15.84 | 0 | 0 | 3 | 4 |
Merc 240D | 24.4 | 4 | 146.7 | 62 | 3.69 | 3.190 | 20.00 | 1 | 0 | 4 | 2 |
Merc 230 | 22.8 | 4 | 140.8 | 95 | 3.92 | 3.150 | 22.90 | 1 | 0 | 4 | 2 |
Merc 280 | 19.2 | 6 | 167.6 | 123 | 3.92 | 3.440 | 18.30 | 1 | 0 | 4 | 4 |
Merc 280C | 17.8 | 6 | 167.6 | 123 | 3.92 | 3.440 | 18.90 | 1 | 0 | 4 | 4 |
Merc 450SE | 16.4 | 8 | 275.8 | 180 | 3.07 | 4.070 | 17.40 | 0 | 0 | 3 | 3 |
Merc 450SL | 17.3 | 8 | 275.8 | 180 | 3.07 | 3.730 | 17.60 | 0 | 0 | 3 | 3 |
Merc 450SLC | 15.2 | 8 | 275.8 | 180 | 3.07 | 3.780 | 18.00 | 0 | 0 | 3 | 3 |
Cadillac Fleetwood | 10.4 | 8 | 472.0 | 205 | 2.93 | 5.250 | 17.98 | 0 | 0 | 3 | 4 |
Lincoln Continental | 10.4 | 8 | 460.0 | 215 | 3.00 | 5.424 | 17.82 | 0 | 0 | 3 | 4 |
Chrysler Imperial | 14.7 | 8 | 440.0 | 230 | 3.23 | 5.345 | 17.42 | 0 | 0 | 3 | 4 |
Fiat 128 | 32.4 | 4 | 78.7 | 66 | 4.08 | 2.200 | 19.47 | 1 | 1 | 4 | 1 |
Honda Civic | 30.4 | 4 | 75.7 | 52 | 4.93 | 1.615 | 18.52 | 1 | 1 | 4 | 2 |
Toyota Corolla | 33.9 | 4 | 71.1 | 65 | 4.22 | 1.835 | 19.90 | 1 | 1 | 4 | 1 |
Toyota Corona | 21.5 | 4 | 120.1 | 97 | 3.70 | 2.465 | 20.01 | 1 | 0 | 3 | 1 |
Dodge Challenger | 15.5 | 8 | 318.0 | 150 | 2.76 | 3.520 | 16.87 | 0 | 0 | 3 | 2 |
AMC Javelin | 15.2 | 8 | 304.0 | 150 | 3.15 | 3.435 | 17.30 | 0 | 0 | 3 | 2 |
Camaro Z28 | 13.3 | 8 | 350.0 | 245 | 3.73 | 3.840 | 15.41 | 0 | 0 | 3 | 4 |
Pontiac Firebird | 19.2 | 8 | 400.0 | 175 | 3.08 | 3.845 | 17.05 | 0 | 0 | 3 | 2 |
Fiat X1-9 | 27.3 | 4 | 79.0 | 66 | 4.08 | 1.935 | 18.90 | 1 | 1 | 4 | 1 |
Porsche 914-2 | 26.0 | 4 | 120.3 | 91 | 4.43 | 2.140 | 16.70 | 0 | 1 | 5 | 2 |
Lotus Europa | 30.4 | 4 | 95.1 | 113 | 3.77 | 1.513 | 16.90 | 1 | 1 | 5 | 2 |
Ford Pantera L | 15.8 | 8 | 351.0 | 264 | 4.22 | 3.170 | 14.50 | 0 | 1 | 5 | 4 |
Ferrari Dino | 19.7 | 6 | 145.0 | 175 | 3.62 | 2.770 | 15.50 | 0 | 1 | 5 | 6 |
Maserati Bora | 15.0 | 8 | 301.0 | 335 | 3.54 | 3.570 | 14.60 | 0 | 1 | 5 | 8 |
Volvo 142E | 21.4 | 4 | 121.0 | 109 | 4.11 | 2.780 | 18.60 | 1 | 1 | 4 | 2 |
Criando uma nova coluna com o nome das linhas
#Vendo o nome das linhas
rownames(dados)
## [1] "Mazda RX4" "Mazda RX4 Wag" "Datsun 710"
## [4] "Hornet 4 Drive" "Hornet Sportabout" "Valiant"
## [7] "Duster 360" "Merc 240D" "Merc 230"
## [10] "Merc 280" "Merc 280C" "Merc 450SE"
## [13] "Merc 450SL" "Merc 450SLC" "Cadillac Fleetwood"
## [16] "Lincoln Continental" "Chrysler Imperial" "Fiat 128"
## [19] "Honda Civic" "Toyota Corolla" "Toyota Corona"
## [22] "Dodge Challenger" "AMC Javelin" "Camaro Z28"
## [25] "Pontiac Firebird" "Fiat X1-9" "Porsche 914-2"
## [28] "Lotus Europa" "Ford Pantera L" "Ferrari Dino"
## [31] "Maserati Bora" "Volvo 142E"
$coluna_nome_carros=rownames(dados)
dados%>% kbl %>% kable_material_dark(full_width = F) dados
mpg | cyl | disp | hp | drat | wt | qsec | vs | am | gear | carb | coluna_nome_carros | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
Mazda RX4 | 21.0 | 6 | 160.0 | 110 | 3.90 | 2.620 | 16.46 | 0 | 1 | 4 | 4 | Mazda RX4 |
Mazda RX4 Wag | 21.0 | 6 | 160.0 | 110 | 3.90 | 2.875 | 17.02 | 0 | 1 | 4 | 4 | Mazda RX4 Wag |
Datsun 710 | 22.8 | 4 | 108.0 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 | 1 | Datsun 710 |
Hornet 4 Drive | 21.4 | 6 | 258.0 | 110 | 3.08 | 3.215 | 19.44 | 1 | 0 | 3 | 1 | Hornet 4 Drive |
Hornet Sportabout | 18.7 | 8 | 360.0 | 175 | 3.15 | 3.440 | 17.02 | 0 | 0 | 3 | 2 | Hornet Sportabout |
Valiant | 18.1 | 6 | 225.0 | 105 | 2.76 | 3.460 | 20.22 | 1 | 0 | 3 | 1 | Valiant |
Duster 360 | 14.3 | 8 | 360.0 | 245 | 3.21 | 3.570 | 15.84 | 0 | 0 | 3 | 4 | Duster 360 |
Merc 240D | 24.4 | 4 | 146.7 | 62 | 3.69 | 3.190 | 20.00 | 1 | 0 | 4 | 2 | Merc 240D |
Merc 230 | 22.8 | 4 | 140.8 | 95 | 3.92 | 3.150 | 22.90 | 1 | 0 | 4 | 2 | Merc 230 |
Merc 280 | 19.2 | 6 | 167.6 | 123 | 3.92 | 3.440 | 18.30 | 1 | 0 | 4 | 4 | Merc 280 |
Merc 280C | 17.8 | 6 | 167.6 | 123 | 3.92 | 3.440 | 18.90 | 1 | 0 | 4 | 4 | Merc 280C |
Merc 450SE | 16.4 | 8 | 275.8 | 180 | 3.07 | 4.070 | 17.40 | 0 | 0 | 3 | 3 | Merc 450SE |
Merc 450SL | 17.3 | 8 | 275.8 | 180 | 3.07 | 3.730 | 17.60 | 0 | 0 | 3 | 3 | Merc 450SL |
Merc 450SLC | 15.2 | 8 | 275.8 | 180 | 3.07 | 3.780 | 18.00 | 0 | 0 | 3 | 3 | Merc 450SLC |
Cadillac Fleetwood | 10.4 | 8 | 472.0 | 205 | 2.93 | 5.250 | 17.98 | 0 | 0 | 3 | 4 | Cadillac Fleetwood |
Lincoln Continental | 10.4 | 8 | 460.0 | 215 | 3.00 | 5.424 | 17.82 | 0 | 0 | 3 | 4 | Lincoln Continental |
Chrysler Imperial | 14.7 | 8 | 440.0 | 230 | 3.23 | 5.345 | 17.42 | 0 | 0 | 3 | 4 | Chrysler Imperial |
Fiat 128 | 32.4 | 4 | 78.7 | 66 | 4.08 | 2.200 | 19.47 | 1 | 1 | 4 | 1 | Fiat 128 |
Honda Civic | 30.4 | 4 | 75.7 | 52 | 4.93 | 1.615 | 18.52 | 1 | 1 | 4 | 2 | Honda Civic |
Toyota Corolla | 33.9 | 4 | 71.1 | 65 | 4.22 | 1.835 | 19.90 | 1 | 1 | 4 | 1 | Toyota Corolla |
Toyota Corona | 21.5 | 4 | 120.1 | 97 | 3.70 | 2.465 | 20.01 | 1 | 0 | 3 | 1 | Toyota Corona |
Dodge Challenger | 15.5 | 8 | 318.0 | 150 | 2.76 | 3.520 | 16.87 | 0 | 0 | 3 | 2 | Dodge Challenger |
AMC Javelin | 15.2 | 8 | 304.0 | 150 | 3.15 | 3.435 | 17.30 | 0 | 0 | 3 | 2 | AMC Javelin |
Camaro Z28 | 13.3 | 8 | 350.0 | 245 | 3.73 | 3.840 | 15.41 | 0 | 0 | 3 | 4 | Camaro Z28 |
Pontiac Firebird | 19.2 | 8 | 400.0 | 175 | 3.08 | 3.845 | 17.05 | 0 | 0 | 3 | 2 | Pontiac Firebird |
Fiat X1-9 | 27.3 | 4 | 79.0 | 66 | 4.08 | 1.935 | 18.90 | 1 | 1 | 4 | 1 | Fiat X1-9 |
Porsche 914-2 | 26.0 | 4 | 120.3 | 91 | 4.43 | 2.140 | 16.70 | 0 | 1 | 5 | 2 | Porsche 914-2 |
Lotus Europa | 30.4 | 4 | 95.1 | 113 | 3.77 | 1.513 | 16.90 | 1 | 1 | 5 | 2 | Lotus Europa |
Ford Pantera L | 15.8 | 8 | 351.0 | 264 | 4.22 | 3.170 | 14.50 | 0 | 1 | 5 | 4 | Ford Pantera L |
Ferrari Dino | 19.7 | 6 | 145.0 | 175 | 3.62 | 2.770 | 15.50 | 0 | 1 | 5 | 6 | Ferrari Dino |
Maserati Bora | 15.0 | 8 | 301.0 | 335 | 3.54 | 3.570 | 14.60 | 0 | 1 | 5 | 8 | Maserati Bora |
Volvo 142E | 21.4 | 4 | 121.0 | 109 | 4.11 | 2.780 | 18.60 | 1 | 1 | 4 | 2 | Volvo 142E |
Criando o gráfico treemap do consumo de Gasolina em Galão por milhas
treemap(dados, index = c('coluna_nome_carros'), vSize = "mpg", title = "Consumo de Gasolina em galão por milhas")
Criando o Mapa de calor com MPG, DISP E HP
#Analisando a variabilidade das variáveis (tonalidade das cores)
=sd(dados$disp)/mean(dados$disp)
cv_disp=sd(dados$hp)/mean(dados$hp)
cv_hp=sd(dados$mpg)/mean(dados$mpg)
cv_mpgcbind(cv_disp,cv_hp,cv_mpg)
## cv_disp cv_hp cv_mpg
## [1,] 0.5371779 0.4674077 0.2999881
<<- as.matrix(dados[,c("mpg","disp","hp")])
dados2 heatmap(dados2)
Gerando wordcloud
= c("Estatística", "Machine Learning", "Redes Neurais",
Palavras "Deep Learning","Random Forest", "SVM","R","Python")
= c(100,50,20,10,20,7,150,150)
Freq
= data.frame(Palavras,Freq)
dados_palavras
#Núvem de palavras
wordcloud(dados_palavras$Palavras,freq = dados_palavras$Freq)
#Adicionando cores e ordem aleatória (random.order=T)
wordcloud(dados_palavras$Palavras,freq = dados_palavras$Freq,random.order=T,colors=brewer.pal(n = 7, name = "YlGn"))
Segunda forma
# criando o novo vetor de palavras e frequências de forma automática
#Criando o vetor de repetições de palavras
= c(rep("Estatística",100), rep("Machine Learning",50), rep("Redes Neurais",20),
Palavras2 rep("Deep Learning",10),rep("Random Forest",20), rep("SVM",7),rep("R",150),rep("Python",150)
)
#Criando as frequências absolutas simples
=table(Palavras2)
tabela=data.frame(tabela)
dados_novo
#Criando a wordcloud
wordcloud(dados_novo$Palavras2,freq = dados_novo$Freq,random.order=T,colors=brewer.pal(n = 7, name = "YlGn"))
Criando Grafos no R
=c("A","B","C","D","E","F")
no=data.frame(origem=c(rep("A",2),rep("B",2),"C","D","E","F"),destino=c("B","D","C","E","D","E","F","B"))
ligacoes
<- graph_from_data_frame(d=ligacoes, vertices=no, directed=F)
rede_teste rede_teste
## IGRAPH 6ead5d5 UN-- 6 8 --
## + attr: name (v/c)
## + edges from 6ead5d5 (vertex names):
## [1] A--B A--D B--C B--E C--D D--E E--F B--F
plot(rede_teste, vertex.label=no,vertex.size=50, layout=layout_as_star(rede_teste),main="Grafo com igraph")
Grafos interativos 2d
library(rgl)
#2d interativo
tkplot(rede_teste)
## [1] 1
Grafos interativos 3d
#3d interativo
rglplot(rede_teste,vertex.label=unique(ligacoes$origem),vertex.size=5, layout=layout_in_circle(rede_teste))
Gráficos point and click (Drag and drop)
#iris
#esquisser(viewer = "browser")