Link: https://github.com/wapsyed/cursor 

Ministrante: Wasim Aluísio Prates Syed, Farmacêutico pela FCFRP-USP, doutorando em biotecnologia pelo ICB/IPT/Butantan, e divulgador científico pela UPVacina e Projeto Halo.

Descrição do curso:

Desenvolvemos um curso para tornar o aprendizado de uma das linguagens de programação e análise de dados mais populares mais acessível, especialmente para aqueles que não têm formação em áreas de exatas, como TI e ciência da computação. Esta linguagem é amplamente utilizada por cientistas devido à sua variedade de ferramentas para análise de dados em ciências biológicas e da saúde. Com uma abordagem prática e interativa, os participantes explorarão conceitos e ferramentas para realizar análises de dados de forma simples e intuitiva. Além disso, terão acesso a um grupo de discussão para compartilhar dúvidas e ideias, criando um ambiente colaborativo e de aprendizado mútuo.

Programação e conteúdo

Os participantes terão uma aula introdutória à ciência de dados e fundamentos da manipulação de dados no R e visualização de dados com o ggplot, no ambiente do RStudio. Em seguida, os participantes terão um tempo para praticar e desenvolver as análises com 5 países de escolha, e no final deverão criar um poster com os gráficos produzidos.

Prática

OBS: Para apresentar de tabelas e imagens fora do Markdown, vá para o Tools > Global options > R Markdown and unselect “Show output inline for all R Markdown documents”

1. Biblioteca e pacotes

2. Operações básicas

#Operações básicas -----

#Variáveis numéricas
x = 5
x
## [1] 5
y = 7
y
## [1] 7
z = y + x
z
## [1] 12
multi = x * y
multi
## [1] 35
# Variáveis textuais (characters, string)
a = "Olá"
a
## [1] "Olá"
b = "Tudo bem?"
b
## [1] "Tudo bem?"
# Variáveis Lógicas
t = TRUE
t
## [1] TRUE
f = FALSE
f
## [1] FALSE
# Comparações lógicas (booleanas)
a == b #Diferente
## [1] FALSE
x < y # Menor
## [1] TRUE
x > y # Maior
## [1] FALSE
x <= 5 # menor ou igual
## [1] TRUE
t == f #Igual
## [1] FALSE
t != f #Diferente
## [1] TRUE

Se criarmos outras variáveis com nomes diferentes, mas com os mesmos valores, elas ainda continuarão dando o mesmo resultado

# Se criarmos outras variáveis com nomes diferentes, mas com os mesmos valores, elas ainda continuarão dando o mesmo resultado
tt = TRUE
ff = FALSE
aa = "Olá"

t == tt #Igual
## [1] TRUE
f == ff #Igual
## [1] TRUE
aa == a #Igual
## [1] TRUE

Vetores

Os vetores são uma sequência unidimensional que podem ser números, strings, valores lógicos, entre outros. Podemos criar vetores com a função c(), de “concatenar”.

# Vetores
i = c(7, 5, 9, 10) #Numérico
i
## [1]  7  5  9 10
j = c("Olá", "Caneta", "Qualificacao") #String
j
## [1] "Olá"          "Caneta"       "Qualificacao"
h = c(7, "olá", 78) #String
h
## [1] "7"   "olá" "78"
# O que esta função faz? Use o "?" antes da função e rode.
?c()
## starting httpd help server ... done

Dataframes e tibbles

Dataframes e tibbles são tabelas comuns e consistem de linhas e colunas de diferentes classes, como números, caracteres e fatores.

As tibbles são diferentes dos dataframes somente em sua apresentação no console e facilitam muito o trabalho com tabelas grandes e largas.

Além disso, a criação do dataframe e da tibble são diferentes visualmente. Veja como a tibble é mais semelhante à forma que imputamos dados no excel.

Para criar um dataframe, usamos a função data.frame().

#Dataframes e tibbles -----

#Dataframe
data = data.frame(
  nome = c("Gabriela", "Júlia", "Beatriz", "Luiza"),
  altura = c(1.59, 1.60, 1.65, 1.73),
  idade = c(30, 25, 31, 32)
)

E para criar uma tibble, usamos a função tribble().

#Tibble
tibble = tribble(
  ~nome, ~altura, ~idade,
  "Gabriela", 1.59,   30,
  "Júlia",   1.60,   25,
  "Beatriz",    1.65,  31,
  "Luiza",  1.73,   32 
  )

É possível transformar quase todo objeto em uma tabela.

Por exemplo, se pegarmos os vetores criados anteriormente e usarmos a função as.data.frame(), será criada uma coluna com o nome do vetor, seguida por linhas contendo os elementos do vetor.

# Vetores em dataframe
as.data.frame(i) #dataframe com coluna numérica
##    i
## 1  7
## 2  5
## 3  9
## 4 10
as.data.frame(j) #dataframe com coluna textual
##              j
## 1          Olá
## 2       Caneta
## 3 Qualificacao
as.data.frame(h) #dataframe com coluna textual, mesmo com valores numéricos
##     h
## 1   7
## 2 olá
## 3  78

Há diferentes formas de se visualizar uma tabela.

A diferença de cada objeto está na visualização no console e no documento. Teste estas linhas de código no documento e no console.

#Visualizando o dataframe -----
# Com print()
print(data) #No documento ou console
##       nome altura idade
## 1 Gabriela   1.59    30
## 2    Júlia   1.60    25
## 3  Beatriz   1.65    31
## 4    Luiza   1.73    32
print(tibble)
## # A tibble: 4 × 3
##   nome     altura idade
##   <chr>     <dbl> <dbl>
## 1 Gabriela   1.59    30
## 2 Júlia      1.6     25
## 3 Beatriz    1.65    31
## 4 Luiza      1.73    32
# Com nome do objeto
data
##       nome altura idade
## 1 Gabriela   1.59    30
## 2    Júlia   1.60    25
## 3  Beatriz   1.65    31
## 4    Luiza   1.73    32
tibble 
## # A tibble: 4 × 3
##   nome     altura idade
##   <chr>     <dbl> <dbl>
## 1 Gabriela   1.59    30
## 2 Júlia      1.6     25
## 3 Beatriz    1.65    31
## 4 Luiza      1.73    32
# Com glimpse(). #Descrição mais completa da tabela
glimpse(data) 
## Rows: 4
## Columns: 3
## $ nome   <chr> "Gabriela", "Júlia", "Beatriz", "Luiza"
## $ altura <dbl> 1.59, 1.60, 1.65, 1.73
## $ idade  <dbl> 30, 25, 31, 32
glimpse(tibble)
## Rows: 4
## Columns: 3
## $ nome   <chr> "Gabriela", "Júlia", "Beatriz", "Luiza"
## $ altura <dbl> 1.59, 1.60, 1.65, 1.73
## $ idade  <dbl> 30, 25, 31, 32
# Com view(). A tabela completa com mais funcionalidades (filtragem manual, pesquisa e ordenamento) abrirá em uma nova janela
view(data) 
view(tibble)

# Selecionando o nome do objeto e segurando Ctrl + Click.
data
##       nome altura idade
## 1 Gabriela   1.59    30
## 2    Júlia   1.60    25
## 3  Beatriz   1.65    31
## 4    Luiza   1.73    32
tibble 
## # A tibble: 4 × 3
##   nome     altura idade
##   <chr>     <dbl> <dbl>
## 1 Gabriela   1.59    30
## 2 Júlia      1.6     25
## 3 Beatriz    1.65    31
## 4 Luiza      1.73    32

Estatísticas gerais da tabela

O R possui uma função muito prática de análise estatística descritiva, a summary().

No entanto, existem outros pacotes que realizam essas análises e até geram relatórios em HTML.

Um deles é o skimr, cuja função skim() gera três outputs, um semelhante ao summary, e outras duas tabelas com a quantidade de valores não disponíveis (NA), estatísticas descritivas, e um histograma.

# Estatísticas gerais 
summary(tibble)
##      nome               altura          idade      
##  Length:4           Min.   :1.590   Min.   :25.00  
##  Class :character   1st Qu.:1.597   1st Qu.:28.75  
##  Mode  :character   Median :1.625   Median :30.50  
##                     Mean   :1.643   Mean   :29.50  
##                     3rd Qu.:1.670   3rd Qu.:31.25  
##                     Max.   :1.730   Max.   :32.00
summary(data)
##      nome               altura          idade      
##  Length:4           Min.   :1.590   Min.   :25.00  
##  Class :character   1st Qu.:1.597   1st Qu.:28.75  
##  Mode  :character   Median :1.625   Median :30.50  
##                     Mean   :1.643   Mean   :29.50  
##                     3rd Qu.:1.670   3rd Qu.:31.25  
##                     Max.   :1.730   Max.   :32.00
# Usando skim
skim(tibble)
Data summary
Name tibble
Number of rows 4
Number of columns 3
_______________________
Column type frequency:
character 1
numeric 2
________________________
Group variables None

Variable type: character

skim_variable n_missing complete_rate min max empty n_unique whitespace
nome 0 1 5 8 0 4 0

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
altura 0 1 1.64 0.06 1.59 1.60 1.62 1.67 1.73 ▇▁▃▁▃
idade 0 1 29.50 3.11 25.00 28.75 30.50 31.25 32.00 ▃▁▁▃▇
skim(data)
Data summary
Name data
Number of rows 4
Number of columns 3
_______________________
Column type frequency:
character 1
numeric 2
________________________
Group variables None

Variable type: character

skim_variable n_missing complete_rate min max empty n_unique whitespace
nome 0 1 5 8 0 4 0

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
altura 0 1 1.64 0.06 1.59 1.60 1.62 1.67 1.73 ▇▁▃▁▃
idade 0 1 29.50 3.11 25.00 28.75 30.50 31.25 32.00 ▃▁▁▃▇

Pivotando tabelas: Long e Wide

As tabelas tidy possuem dois formatos, um largo (wide) e outro longo (long). Converter uma em outra é conhecido como pivotagem, e conhecer essas funções é importantíssimo para obter, manipular e explorar dados.

Para pivotar, utilizamos pivot_longer() e pivot_wider(). A pivotagem deve ser pensada com base na relação entre variáveis e seus valores.

Por exemplo, se tivermos uma tabela larga com 10 colunas com anos (de 1990 a 2000), podemos reduzi-las em uma só coluna chamada “anos”, que facilitará a manipulação de dados. Isso alongará a tabela.

Mas, se quisermos deixá-la mais fácil de ser interpretada por humanos, podemos pivotá-la em uma tabela larga.

# Trabalhando com dataframes -----
#Transformando outros formatos em dataframe

# Long table
data_long = pivot_longer(data, #Tabela 
             cols = c(altura, idade), #Colunas para alongar 
             values_to = "valor", # Estocar valores em uma nova coluna
             names_to = "variavel" # Estocar variáveis em uma nova coluna
             ) 
data_long
## # A tibble: 8 × 3
##   nome     variavel valor
##   <chr>    <chr>    <dbl>
## 1 Gabriela altura    1.59
## 2 Gabriela idade    30   
## 3 Júlia    altura    1.6 
## 4 Júlia    idade    25   
## 5 Beatriz  altura    1.65
## 6 Beatriz  idade    31   
## 7 Luiza    altura    1.73
## 8 Luiza    idade    32
# Wide table
data_wide = pivot_wider(data_long, #Tabela
            names_from = variavel, #Dividir níveis de uma coluna em novas colunas
            values_from = valor)   #Estocar valores relacionados à coluna nome e novas variáveis) 

Matrizes

As matrizes são estruturas tabelares cujos valores são somente numéricos. Para isso, é necessário converter a coluna de “nomes” (strings) em nomes de linhas (rownames) usando o column_to_rownames(), e então converter a tabela em matriz, com o as.matrix().

A diferença aqui é a apresentação da tabela. Enquanto dataframes e tibbles são facilmente lidas, as matrizes são mais complicadas nesse sentido.

Caso você queira manipular a matriz com as funções do tidyverse, é recomendável reconvertê-la em dataframe/tibble, manipular os dados, e depois converter novamente para matriz.

É importante saber manipular matrizes para computar análises estatísticas, como o Principal Components Analysis, por exemplo.

#Matriz
matrix = as.matrix(data) #Transformar tabela em matriz
matrix #Os valores numéricos são strings
##      nome       altura idade
## [1,] "Gabriela" "1.59" "30" 
## [2,] "Júlia"    "1.60" "25" 
## [3,] "Beatriz"  "1.65" "31" 
## [4,] "Luiza"    "1.73" "32"
data_matrix = column_to_rownames(data, "nome") #Converte coluna em rownames
matrix = as.matrix(data_matrix)
matrix #Agora, os valores são numéricos
##          altura idade
## Gabriela   1.59    30
## Júlia      1.60    25
## Beatriz    1.65    31
## Luiza      1.73    32
# Reconverter para dataframe
matrix_dr = as.data.frame(matrix)

matrix_dr # Coluna "nome" continua como rownames e dificulta a manipulação.
##          altura idade
## Gabriela   1.59    30
## Júlia      1.60    25
## Beatriz    1.65    31
## Luiza      1.73    32
matrix_dr = rownames_to_column(matrix_dr, "nome") #Converter rownames em nova coluna
matrix_dr
##       nome altura idade
## 1 Gabriela   1.59    30
## 2    Júlia   1.60    25
## 3  Beatriz   1.65    31
## 4    Luiza   1.73    32

Listas

Listas são estruturas que podem conter um conjunto de elementos de diferentes classes, como vetores, outras listas, dataframes, e matrizes.

Elas são interessantes para organizar os objetos necessários para uma análise, e são muito comuns em análises de RNAseq, por exemplo.

#Criando a lista
lista = list(a, b, f, h, j, multi, t, data, matrix, tibble)

#View(lista) #Visualizando a lista

#Acessando objetos diferentes da lista
lista[[1]] #Primeiro objeto
## [1] "Olá"
lista[[8]] #Oitavo objeto
##       nome altura idade
## 1 Gabriela   1.59    30
## 2    Júlia   1.60    25
## 3  Beatriz   1.65    31
## 4    Luiza   1.73    32
#Isolando o objeto
df_list = lista[[8]]
df_list
##       nome altura idade
## 1 Gabriela   1.59    30
## 2    Júlia   1.60    25
## 3  Beatriz   1.65    31
## 4    Luiza   1.73    32

Manipulação de tabelas com o R base

O R possui funções e formas nativas de acessar e manipular tabelas. Essas operações, como as descritas abaixo, não são mais a melhor forma de trabalhar, pois são pouco intuitivas. Mas, é importante conhecê-las, pois, são utilizadas em alguns casos.

# Acessando colunas do data frame
data$nome
## [1] "Gabriela" "Júlia"    "Beatriz"  "Luiza"
data$idade
## [1] 30 25 31 32
# Criando nova variável para não sobrescrever a tabela original para os próximos exemplos
data_2 = data

# Adicionando uma nova coluna ao data frame
data_2$peso = c(70, 
                65, 
                80, 
                20)
data_2
##       nome altura idade peso
## 1 Gabriela   1.59    30   70
## 2    Júlia   1.60    25   65
## 3  Beatriz   1.65    31   80
## 4    Luiza   1.73    32   20
# Removendo uma coluna do data frame
data_2 = data_2[ , -4]

# Filtrando linhas do data frame. df[linha, coluna]
data_jovens = data_2[data_2$idade < 30, ]
data_jovens
##    nome altura idade
## 2 Júlia    1.6    25
# Ordenando o data frame por uma coluna
data_ordenados <- data_2[order(data_2$idade), ]
data_ordenados
##       nome altura idade
## 2    Júlia   1.60    25
## 1 Gabriela   1.59    30
## 3  Beatriz   1.65    31
## 4    Luiza   1.73    32

3. Tidyverse

O tidyverse é um metapacote, um pacote com diversos pacotes dentro, que facilita muito o trabalho no R. As funções conversam entre si, são padronizadas e, mais importante, são muito intuitivas.

Adicionando linhas e colunas

Para adicionar uma linha com valores, usamos o add_row(), e para adicionar uma coluna, o add_column. Bem intuitivo, né?

Para não alterarmos as tabelas originais, criamos uma nova variável chamada data_2 e tibble_2.

#Adicionar linha
data_2 = add_row(data, 
               nome = "Rafaela", 
               idade = 50,
               altura = 1.85)

tibble_2 = add_row(tibble, 
                   nome = "Rafaela", 
                   idade = 50,
                   altura = 1.85)

data_2
##       nome altura idade
## 1 Gabriela   1.59    30
## 2    Júlia   1.60    25
## 3  Beatriz   1.65    31
## 4    Luiza   1.73    32
## 5  Rafaela   1.85    50
tibble_2
## # A tibble: 5 × 3
##   nome     altura idade
##   <chr>     <dbl> <dbl>
## 1 Gabriela   1.59    30
## 2 Júlia      1.6     25
## 3 Beatriz    1.65    31
## 4 Luiza      1.73    32
## 5 Rafaela    1.85    50
#Adicionar coluna
data_2 = add_column(data_2,
                    peso = c(50,
                             80,
                             40,
                             100,
                             70))

tibble_2 = add_column(tibble_2,
                      peso = c(50,
                               80,
                               40,
                               100,
                               70))

data_2
##       nome altura idade peso
## 1 Gabriela   1.59    30   50
## 2    Júlia   1.60    25   80
## 3  Beatriz   1.65    31   40
## 4    Luiza   1.73    32  100
## 5  Rafaela   1.85    50   70
tibble_2
## # A tibble: 5 × 4
##   nome     altura idade  peso
##   <chr>     <dbl> <dbl> <dbl>
## 1 Gabriela   1.59    30    50
## 2 Júlia      1.6     25    80
## 3 Beatriz    1.65    31    40
## 4 Luiza      1.73    32   100
## 5 Rafaela    1.85    50    70

filter(): Filtrando linhas e usando o pipe

Sempre que estivermos manipulando linhas, utilizamos o verbo “filtrar”. No tidyverse, mais especificamente no pacote dplyr, usamos a função filter() e estabelecemos argumentos lógicos para a filtragem.

# Filtrando linhas ----
idade = filter(data, idade >= 30)
idade_nome = filter(idade, nome == "Júlia")

Mas, e se eu quiser filtrar usando mais operações?

Temos duas formas de fazer isso.

A primeira é usando “OU” e %in% c().

# Filtrando mais de um valor usando | (OU) e "%in% c()"
data %>%                   #Tenho este objeto
  filter(nome == "Júlia" | # E então vou filtrar indivíduos que tenham o nome "Júlia" OU 
           nome == "Gabriela") #"Gabriela"
##       nome altura idade
## 1 Gabriela   1.59    30
## 2    Júlia   1.60    25
data %>%  
  filter(nome %in% c(     # Filtrando os valores "Júlia" OU "Gabriela" dentro (%in%) da coluna "nome" 
    "Júlia", 
    "Gabriela")) 
##       nome altura idade
## 1 Gabriela   1.59    30
## 2    Júlia   1.60    25

E a segunda é usando o pipe (%>%), que permite “costurar” operações e resultados. Dessa forma, não precisamos criar uma variável/objeto sempre que uma função for aplicada. Usaremos muito o pipe nos próximos códigos.

Abaixo, pegamos uma tabela, filtramos por idade e, então, filtramos somente linhas que não contêm um valor.

# Usando o pipe "%>%" (lê-se "e então")
data %>%                   # Tenho este objeto 
  filter(idade >= 30) %>%  # E então vou filtrar os indivíduos com menos de 30 anos
  filter(nome != "Júlia")   # E então vou filtrar os indivíduos que não incluam a "Júlia"
##       nome altura idade
## 1 Gabriela   1.59    30
## 2  Beatriz   1.65    31
## 3    Luiza   1.73    32

select(): Selecionando colunas

Da mesma forma que trabalhamos com linhas usando filter(), ao trabalhar com colunas, usamos o select().

A função select é muito versátil, e além de selecionar colunas que você quer trabalhar, podemos reordená-las e renomeá-las.

Mas, cuidado, pois ao renomeá-las, se esquecermos do “everything()”, ficamos somente com a coluna renomeada.

Por isso, temos a função rename(), que evita que isso aconteça.

# Selecionando colunas ----
# Selecionar colunas específicas
data_2 %>%
  select(nome, altura) 
##       nome altura
## 1 Gabriela   1.59
## 2    Júlia   1.60
## 3  Beatriz   1.65
## 4    Luiza   1.73
## 5  Rafaela   1.85
# Selecionar da coluna nome (1) à coluna peso (3)
data_2 %>% 
  select(nome:peso) 
##       nome altura idade peso
## 1 Gabriela   1.59    30   50
## 2    Júlia   1.60    25   80
## 3  Beatriz   1.65    31   40
## 4    Luiza   1.73    32  100
## 5  Rafaela   1.85    50   70
#Retirando coluna
data_2 %>% 
  select(-idade) 
##       nome altura peso
## 1 Gabriela   1.59   50
## 2    Júlia   1.60   80
## 3  Beatriz   1.65   40
## 4    Luiza   1.73  100
## 5  Rafaela   1.85   70
data_2 %>%   
  select(!idade)
##       nome altura peso
## 1 Gabriela   1.59   50
## 2    Júlia   1.60   80
## 3  Beatriz   1.65   40
## 4    Luiza   1.73  100
## 5  Rafaela   1.85   70
#Reordenando coluna
data_2 %>%   
  select(idade, everything())
##   idade     nome altura peso
## 1    30 Gabriela   1.59   50
## 2    25    Júlia   1.60   80
## 3    31  Beatriz   1.65   40
## 4    32    Luiza   1.73  100
## 5    50  Rafaela   1.85   70
#Renomeando coluna
data_2 %>%   
  select(age = idade, everything())
##   age     nome altura peso
## 1  30 Gabriela   1.59   50
## 2  25    Júlia   1.60   80
## 3  31  Beatriz   1.65   40
## 4  32    Luiza   1.73  100
## 5  50  Rafaela   1.85   70
#Renomeando coluna com rename
data_2 %>%   
  rename(age = idade) #Retirando coluna
##       nome altura age peso
## 1 Gabriela   1.59  30   50
## 2    Júlia   1.60  25   80
## 3  Beatriz   1.65  31   40
## 4    Luiza   1.73  32  100
## 5  Rafaela   1.85  50   70

mutate(): Criando e realizando operações com novas variáveis

A função mutate() permite criar ou modificar colunas e imputar valores usando funções que se aplicarão a todas as linhas daquela coluna.

# Criando novas variáveis
data_2 = data_2 %>%
  mutate(imc = peso / (altura^2)) #Para cada linha da tabela, pegaremos o valor do peso e dividiremos pela altura ao quadrado.

data_2 %>% 
  mutate(sexo = "feminino") #Como todas as linhas contêm nomes femininos, criaremos a coluna sexo com o valor "feminino"
##       nome altura idade peso      imc     sexo
## 1 Gabriela   1.59    30   50 19.77770 feminino
## 2    Júlia   1.60    25   80 31.25000 feminino
## 3  Beatriz   1.65    31   40 14.69238 feminino
## 4    Luiza   1.73    32  100 33.41241 feminino
## 5  Rafaela   1.85    50   70 20.45289 feminino

summarize(): resumindo estatísticas

A função summarize (ou summarise) aplica a mesma lógica, mas a tabela gerada é muito menor, e se aplica à variável de interesse na tabela. Por exemplo, se quisermos obter a média (mean()), e a soma (sum()) das linhas de uma coluna, a summarize é capaz de fazer isso.

# Resumindo dados
data_2 %>% 
  summarize(Media_idade = mean(idade))
##   Media_idade
## 1        33.6
data_2 %>% 
  summarize(Soma_idade = sum(idade))
##   Soma_idade
## 1        168

arrange(): Ordenando dados

# Ordenando dados de forma crescente
data_2 %>% 
  arrange(idade)
##       nome altura idade peso      imc
## 1    Júlia   1.60    25   80 31.25000
## 2 Gabriela   1.59    30   50 19.77770
## 3  Beatriz   1.65    31   40 14.69238
## 4    Luiza   1.73    32  100 33.41241
## 5  Rafaela   1.85    50   70 20.45289
# Ordenando de forma decrescente
#Método 1
data_2 %>% 
  arrange(desc(idade))
##       nome altura idade peso      imc
## 1  Rafaela   1.85    50   70 20.45289
## 2    Luiza   1.73    32  100 33.41241
## 3  Beatriz   1.65    31   40 14.69238
## 4 Gabriela   1.59    30   50 19.77770
## 5    Júlia   1.60    25   80 31.25000
#Método 2
data_2 %>% 
  arrange(-idade)
##       nome altura idade peso      imc
## 1  Rafaela   1.85    50   70 20.45289
## 2    Luiza   1.73    32  100 33.41241
## 3  Beatriz   1.65    31   40 14.69238
## 4 Gabriela   1.59    30   50 19.77770
## 5    Júlia   1.60    25   80 31.25000

Usando o pipe para fazer múltiplas operações de uma vez

Usando o pipe, podemos escrever e ler códigos em uma sequência lógica fácil.

Por exemplo, abaixo:

pegamos a tabela data_2, ordenamos a altura na ordem crescente,

filtramos somente as pessoas com idade acima de 30 e peso acima de 50 e retiramos os nomes.

Depois, arredondamos os valores do IMC para uma casa decimal (usando round()) e criamos uma nova variável chamada peso versus idade.

Por fim, resumimos os dados usando a média do peso e a média do imc.

# Múltiplas operações em uma caixa
data_2 %>% 
  arrange(altura) %>% 
  filter(idade >= 30,
         peso >= 50) %>% 
  select(-nome) %>% 
  mutate(imc = round(imc, 1),
         peso_x_idade = peso * idade) %>%
  summarise(mean_peso = mean(peso) %>% round(1),
            mean_imc = mean(imc) %>% round(1))
##   mean_peso mean_imc
## 1      73.3     24.6

4. Trabalhando com dados reais

Importando e padronizando tabela

#Pelo readr
cobertura_vacinal_unicef <- read_csv("cobertura_vacinal_unicef.csv") 
## Rows: 103066 Columns: 6
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (4): country, unicef_region, iso3, vaccine
## dbl (2): year, cov
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
#Manual: File > Import Dataset > From text (readr)
cobertura_vacinal_unicef
## # A tibble: 103,066 × 6
##    country      year   cov unicef_region iso3  vaccine
##    <chr>       <dbl> <dbl> <chr>         <chr> <chr>  
##  1 Afghanistan  2022    88 ROSA          AFG   BCG    
##  2 Afghanistan  2021    84 ROSA          AFG   BCG    
##  3 Afghanistan  2020    87 ROSA          AFG   BCG    
##  4 Afghanistan  2019    86 ROSA          AFG   BCG    
##  5 Afghanistan  2018    89 ROSA          AFG   BCG    
##  6 Afghanistan  2017    84 ROSA          AFG   BCG    
##  7 Afghanistan  2016    78 ROSA          AFG   BCG    
##  8 Afghanistan  2015    76 ROSA          AFG   BCG    
##  9 Afghanistan  2014    74 ROSA          AFG   BCG    
## 10 Afghanistan  2013    72 ROSA          AFG   BCG    
## # ℹ 103,056 more rows
data_long = cobertura_vacinal_unicef 

Explorando dados

Visualizando tabelas

# Explorando dados -----

# Tabela completa
view(data_long) 

# Descrição geral
glimpse(data_long)
## Rows: 103,066
## Columns: 6
## $ country       <chr> "Afghanistan", "Afghanistan", "Afghanistan", "Afghanista…
## $ year          <dbl> 2022, 2021, 2020, 2019, 2018, 2017, 2016, 2015, 2014, 20…
## $ cov           <dbl> 88, 84, 87, 86, 89, 84, 78, 76, 74, 72, 78, 71, 68, 64, …
## $ unicef_region <chr> "ROSA", "ROSA", "ROSA", "ROSA", "ROSA", "ROSA", "ROSA", …
## $ iso3          <chr> "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", …
## $ vaccine       <chr> "BCG", "BCG", "BCG", "BCG", "BCG", "BCG", "BCG", "BCG", …
# Primeiras 10 linhas
head(data_long, 10)
## # A tibble: 10 × 6
##    country      year   cov unicef_region iso3  vaccine
##    <chr>       <dbl> <dbl> <chr>         <chr> <chr>  
##  1 Afghanistan  2022    88 ROSA          AFG   BCG    
##  2 Afghanistan  2021    84 ROSA          AFG   BCG    
##  3 Afghanistan  2020    87 ROSA          AFG   BCG    
##  4 Afghanistan  2019    86 ROSA          AFG   BCG    
##  5 Afghanistan  2018    89 ROSA          AFG   BCG    
##  6 Afghanistan  2017    84 ROSA          AFG   BCG    
##  7 Afghanistan  2016    78 ROSA          AFG   BCG    
##  8 Afghanistan  2015    76 ROSA          AFG   BCG    
##  9 Afghanistan  2014    74 ROSA          AFG   BCG    
## 10 Afghanistan  2013    72 ROSA          AFG   BCG
# Últimas 10 linhas
tail(data_long, 10)
## # A tibble: 10 × 6
##    country  year   cov unicef_region iso3  vaccine
##    <chr>   <dbl> <dbl> <chr>         <chr> <chr>  
##  1 WCAR     2022    28 WCAR          <NA>  HEPBB  
##  2 WCAR     2022    69 WCAR          <NA>  HIB3   
##  3 WCAR     2022    70 WCAR          <NA>  IPV1   
##  4 WCAR     2022    64 WCAR          <NA>  MCV1   
##  5 WCAR     2022    32 WCAR          <NA>  MCV2   
##  6 WCAR     2022    64 WCAR          <NA>  PCV3   
##  7 WCAR     2022    68 WCAR          <NA>  POL3   
##  8 WCAR     2022    20 WCAR          <NA>  RCV1   
##  9 WCAR     2022    44 WCAR          <NA>  ROTAC  
## 10 WCAR     2022    62 WCAR          <NA>  YFV
#Summary statistics
summary(data_long)
##    country               year           cov        unicef_region     
##  Length:103066      Min.   :1980   Min.   : 0.00   Length:103066     
##  Class :character   1st Qu.:1990   1st Qu.:75.00   Class :character  
##  Mode  :character   Median :2001   Median :90.00   Mode  :character  
##                     Mean   :2001   Mean   :81.46                     
##                     3rd Qu.:2012   3rd Qu.:97.00                     
##                     Max.   :2022   Max.   :99.00                     
##                                    NA's   :39349                     
##      iso3             vaccine         
##  Length:103066      Length:103066     
##  Class :character   Class :character  
##  Mode  :character   Mode  :character  
##                                       
##                                       
##                                       
## 
#Níveis de colunas
unique(data_long$unicef_region)
## [1] "ROSA"          "ECAR"          "MENA"          "ESAR"         
## [5] "LACR"          "Non-programme" "WCAR"          "EAPR"         
## [9] "Global"
unique(data_long$country)
##   [1] "Afghanistan"                          
##   [2] "Albania"                              
##   [3] "Algeria"                              
##   [4] "Angola"                               
##   [5] "Argentina"                            
##   [6] "Armenia"                              
##   [7] "Austria"                              
##   [8] "Azerbaijan"                           
##   [9] "Bangladesh"                           
##  [10] "Belarus"                              
##  [11] "Belize"                               
##  [12] "Benin"                                
##  [13] "Bhutan"                               
##  [14] "Bolivia (Plurinational State of)"     
##  [15] "Bosnia and Herzegovina"               
##  [16] "Botswana"                             
##  [17] "Brazil"                               
##  [18] "Brunei Darussalam"                    
##  [19] "Bulgaria"                             
##  [20] "Burkina Faso"                         
##  [21] "Burundi"                              
##  [22] "Cabo Verde"                           
##  [23] "Cambodia"                             
##  [24] "Cameroon"                             
##  [25] "Central African Republic"             
##  [26] "Chad"                                 
##  [27] "Chile"                                
##  [28] "China"                                
##  [29] "Colombia"                             
##  [30] "Comoros"                              
##  [31] "Congo"                                
##  [32] "Cook Islands"                         
##  [33] "Costa Rica"                           
##  [34] "Cote d'Ivoire"                        
##  [35] "Croatia"                              
##  [36] "Cuba"                                 
##  [37] "Czechia"                              
##  [38] "Democratic People's Republic of Korea"
##  [39] "Democratic Republic of the Congo"     
##  [40] "Djibouti"                             
##  [41] "Dominica"                             
##  [42] "Dominican Republic"                   
##  [43] "Ecuador"                              
##  [44] "Egypt"                                
##  [45] "El Salvador"                          
##  [46] "Equatorial Guinea"                    
##  [47] "Eritrea"                              
##  [48] "Estonia"                              
##  [49] "Eswatini"                             
##  [50] "Ethiopia"                             
##  [51] "Fiji"                                 
##  [52] "Finland"                              
##  [53] "France"                               
##  [54] "Gabon"                                
##  [55] "Gambia"                               
##  [56] "Georgia"                              
##  [57] "Ghana"                                
##  [58] "Greece"                               
##  [59] "Guatemala"                            
##  [60] "Guinea"                               
##  [61] "Guinea-Bissau"                        
##  [62] "Guyana"                               
##  [63] "Haiti"                                
##  [64] "Honduras"                             
##  [65] "Hungary"                              
##  [66] "India"                                
##  [67] "Indonesia"                            
##  [68] "Iran (Islamic Republic of)"           
##  [69] "Iraq"                                 
##  [70] "Ireland"                              
##  [71] "Israel"                               
##  [72] "Jamaica"                              
##  [73] "Japan"                                
##  [74] "Jordan"                               
##  [75] "Kazakhstan"                           
##  [76] "Kenya"                                
##  [77] "Kiribati"                             
##  [78] "Kuwait"                               
##  [79] "Kyrgyzstan"                           
##  [80] "Lao People's Democratic Republic"     
##  [81] "Latvia"                               
##  [82] "Lesotho"                              
##  [83] "Liberia"                              
##  [84] "Libya"                                
##  [85] "Lithuania"                            
##  [86] "Madagascar"                           
##  [87] "Malawi"                               
##  [88] "Malaysia"                             
##  [89] "Maldives"                             
##  [90] "Mali"                                 
##  [91] "Malta"                                
##  [92] "Marshall Islands"                     
##  [93] "Mauritania"                           
##  [94] "Mauritius"                            
##  [95] "Mexico"                               
##  [96] "Micronesia (Federated States of)"     
##  [97] "Monaco"                               
##  [98] "Mongolia"                             
##  [99] "Montenegro"                           
## [100] "Morocco"                              
## [101] "Mozambique"                           
## [102] "Myanmar"                              
## [103] "Namibia"                              
## [104] "Nauru"                                
## [105] "Nepal"                                
## [106] "Nicaragua"                            
## [107] "Niger"                                
## [108] "Nigeria"                              
## [109] "Niue"                                 
## [110] "North Macedonia"                      
## [111] "Oman"                                 
## [112] "Pakistan"                             
## [113] "Panama"                               
## [114] "Papua New Guinea"                     
## [115] "Paraguay"                             
## [116] "Peru"                                 
## [117] "Philippines"                          
## [118] "Poland"                               
## [119] "Portugal"                             
## [120] "Qatar"                                
## [121] "Republic of Korea"                    
## [122] "Republic of Moldova"                  
## [123] "Romania"                              
## [124] "Russian Federation"                   
## [125] "Rwanda"                               
## [126] "Saint Kitts and Nevis"                
## [127] "Saint Lucia"                          
## [128] "Saint Vincent and the Grenadines"     
## [129] "Samoa"                                
## [130] "Sao Tome and Principe"                
## [131] "Saudi Arabia"                         
## [132] "Senegal"                              
## [133] "Serbia"                               
## [134] "Seychelles"                           
## [135] "Sierra Leone"                         
## [136] "Singapore"                            
## [137] "Slovakia"                             
## [138] "Slovenia"                             
## [139] "Solomon Islands"                      
## [140] "Somalia"                              
## [141] "South Africa"                         
## [142] "South Sudan"                          
## [143] "Sri Lanka"                            
## [144] "State of Palestine"                   
## [145] "Sudan"                                
## [146] "Sweden"                               
## [147] "Syrian Arab Republic"                 
## [148] "Tajikistan"                           
## [149] "Thailand"                             
## [150] "Timor-Leste"                          
## [151] "Togo"                                 
## [152] "Tonga"                                
## [153] "Tunisia"                              
## [154] "Turkiye"                              
## [155] "Turkmenistan"                         
## [156] "Tuvalu"                               
## [157] "Uganda"                               
## [158] "Ukraine"                              
## [159] "United Arab Emirates"                 
## [160] "United Republic of Tanzania"          
## [161] "Uruguay"                              
## [162] "Uzbekistan"                           
## [163] "Vanuatu"                              
## [164] "Venezuela (Bolivarian Republic of)"   
## [165] "Viet Nam"                             
## [166] "Yemen"                                
## [167] "Zambia"                               
## [168] "Zimbabwe"                             
## [169] "Andorra"                              
## [170] "Antigua and Barbuda"                  
## [171] "Australia"                            
## [172] "Bahamas"                              
## [173] "Bahrain"                              
## [174] "Barbados"                             
## [175] "Belgium"                              
## [176] "Canada"                               
## [177] "Cyprus"                               
## [178] "Denmark"                              
## [179] "Germany"                              
## [180] "Grenada"                              
## [181] "Iceland"                              
## [182] "Italy"                                
## [183] "Lebanon"                              
## [184] "Luxembourg"                           
## [185] "Netherlands (Kingdom of the)"         
## [186] "New Zealand"                          
## [187] "Norway"                               
## [188] "Palau"                                
## [189] "San Marino"                           
## [190] "Spain"                                
## [191] "Suriname"                             
## [192] "Switzerland"                          
## [193] "Trinidad and Tobago"                  
## [194] "United Kingdom"                       
## [195] "United States"                        
## [196] "Global"                               
## [197] "EAPR"                                 
## [198] "ECAR"                                 
## [199] "ESAR"                                 
## [200] "LACR"                                 
## [201] "MENA"                                 
## [202] "Non-programme"                        
## [203] "ROSA"                                 
## [204] "WCAR"
unique(data_long$vaccine)
##  [1] "BCG"   "DTP1"  "DTP3"  "HEPB3" "HEPBB" "HIB3"  "IPV1"  "MCV1"  "MCV2" 
## [10] "PCV3"  "POL3"  "RCV1"  "ROTAC" "YFV"
#Contar linhas por coluna
data_long %>% count(country) 
## # A tibble: 204 × 2
##    country                 n
##    <chr>               <int>
##  1 Afghanistan           516
##  2 Albania               559
##  3 Algeria               516
##  4 Andorra               473
##  5 Angola                559
##  6 Antigua and Barbuda   430
##  7 Argentina             602
##  8 Armenia               559
##  9 Australia             473
## 10 Austria               473
## # ℹ 194 more rows
data_long %>% count(vaccine) 
## # A tibble: 14 × 2
##    vaccine     n
##    <chr>   <int>
##  1 BCG      7611
##  2 DTP1     8772
##  3 DTP3     8772
##  4 HEPB3    8555
##  5 HEPBB    4808
##  6 HIB3     8639
##  7 IPV1     8457
##  8 MCV1     8772
##  9 MCV2     8248
## 10 PCV3     6800
## 11 POL3     8772
## 12 RCV1     7869
## 13 ROTAC    5270
## 14 YFV      1721
data_long %>% count(unicef_region) 
## # A tibble: 9 × 2
##   unicef_region     n
##   <chr>         <int>
## 1 EAPR          15551
## 2 ECAR          11337
## 3 ESAR          12008
## 4 Global          441
## 5 LACR          17727
## 6 MENA          10761
## 7 Non-programme 17916
## 8 ROSA           4371
## 9 WCAR          12954
#Tabela de frequências
table(data_long$country)
## 
##                           Afghanistan                               Albania 
##                                   516                                   559 
##                               Algeria                               Andorra 
##                                   516                                   473 
##                                Angola                   Antigua and Barbuda 
##                                   559                                   430 
##                             Argentina                               Armenia 
##                                   602                                   559 
##                             Australia                               Austria 
##                                   473                                   473 
##                            Azerbaijan                               Bahamas 
##                                   516                                   473 
##                               Bahrain                            Bangladesh 
##                                   516                                   473 
##                              Barbados                               Belarus 
##                                   430                                   473 
##                               Belgium                                Belize 
##                                   473                                   473 
##                                 Benin                                Bhutan 
##                                   559                                   516 
##      Bolivia (Plurinational State of)                Bosnia and Herzegovina 
##                                   559                                   430 
##                              Botswana                                Brazil 
##                                   559                                   602 
##                     Brunei Darussalam                              Bulgaria 
##                                   473                                   559 
##                          Burkina Faso                               Burundi 
##                                   602                                   516 
##                            Cabo Verde                              Cambodia 
##                                   473                                   516 
##                              Cameroon                                Canada 
##                                   559                                   473 
##              Central African Republic                                  Chad 
##                                   430                                   430 
##                                 Chile                                 China 
##                                   516                                   430 
##                              Colombia                               Comoros 
##                                   602                                   430 
##                                 Congo                          Cook Islands 
##                                   559                                   473 
##                            Costa Rica                         Cote d'Ivoire 
##                                   559                                   602 
##                               Croatia                                  Cuba 
##                                   516                                   473 
##                                Cyprus                               Czechia 
##                                   430                                   430 
## Democratic People's Republic of Korea      Democratic Republic of the Congo 
##                                   430                                   473 
##                               Denmark                              Djibouti 
##                                   387                                   516 
##                              Dominica                    Dominican Republic 
##                                   473                                   559 
##                                  EAPR                                  ECAR 
##                                   415                                   415 
##                               Ecuador                                 Egypt 
##                                   602                                   473 
##                           El Salvador                     Equatorial Guinea 
##                                   559                                   430 
##                               Eritrea                                  ESAR 
##                                   516                                   441 
##                               Estonia                              Eswatini 
##                                   473                                   516 
##                              Ethiopia                                  Fiji 
##                                   473                                   559 
##                               Finland                                France 
##                                   473                                   473 
##                                 Gabon                                Gambia 
##                                   387                                   602 
##                               Georgia                               Germany 
##                                   559                                   473 
##                                 Ghana                                Global 
##                                   559                                   441 
##                                Greece                               Grenada 
##                                   516                                   430 
##                             Guatemala                                Guinea 
##                                   559                                   430 
##                         Guinea-Bissau                                Guyana 
##                                   516                                   602 
##                                 Haiti                              Honduras 
##                                   516                                   559 
##                               Hungary                               Iceland 
##                                   430                                   387 
##                                 India                             Indonesia 
##                                   559                                   516 
##            Iran (Islamic Republic of)                                  Iraq 
##                                   473                                   559 
##                               Ireland                                Israel 
##                                   473                                   559 
##                                 Italy                               Jamaica 
##                                   473                                   430 
##                                 Japan                                Jordan 
##                                   516                                   473 
##                            Kazakhstan                                 Kenya 
##                                   516                                   559 
##                              Kiribati                                Kuwait 
##                                   559                                   559 
##                            Kyrgyzstan                                  LACR 
##                                   559                                   441 
##      Lao People's Democratic Republic                                Latvia 
##                                   516                                   559 
##                               Lebanon                               Lesotho 
##                                   473                                   516 
##                               Liberia                                 Libya 
##                                   516                                   516 
##                             Lithuania                            Luxembourg 
##                                   559                                   473 
##                            Madagascar                                Malawi 
##                                   473                                   516 
##                              Malaysia                              Maldives 
##                                   516                                   473 
##                                  Mali                                 Malta 
##                                   516                                   473 
##                      Marshall Islands                            Mauritania 
##                                   559                                   473 
##                             Mauritius                                  MENA 
##                                   516                                   441 
##                                Mexico      Micronesia (Federated States of) 
##                                   559                                   559 
##                                Monaco                              Mongolia 
##                                   430                                   516 
##                            Montenegro                               Morocco 
##                                   430                                   559 
##                            Mozambique                               Myanmar 
##                                   516                                   559 
##                               Namibia                                 Nauru 
##                                   559                                   559 
##                                 Nepal          Netherlands (Kingdom of the) 
##                                   516                                   430 
##                           New Zealand                             Nicaragua 
##                                   473                                   516 
##                                 Niger                               Nigeria 
##                                   516                                   559 
##                                  Niue                         Non-programme 
##                                   559                                   415 
##                       North Macedonia                                Norway 
##                                   559                                   473 
##                                  Oman                              Pakistan 
##                                   516                                   473 
##                                 Palau                                Panama 
##                                   516                                   602 
##                      Papua New Guinea                              Paraguay 
##                                   516                                   559 
##                                  Peru                           Philippines 
##                                   602                                   559 
##                                Poland                              Portugal 
##                                   516                                   516 
##                                 Qatar                     Republic of Korea 
##                                   559                                   516 
##                   Republic of Moldova                               Romania 
##                                   559                                   516 
##                                  ROSA                    Russian Federation 
##                                   415                                   473 
##                                Rwanda                 Saint Kitts and Nevis 
##                                   516                                   473 
##                           Saint Lucia      Saint Vincent and the Grenadines 
##                                   473                                   473 
##                                 Samoa                            San Marino 
##                                   559                                   430 
##                 Sao Tome and Principe                          Saudi Arabia 
##                                   602                                   559 
##                               Senegal                                Serbia 
##                                   602                                   516 
##                            Seychelles                          Sierra Leone 
##                                   516                                   559 
##                             Singapore                              Slovakia 
##                                   516                                   473 
##                              Slovenia                       Solomon Islands 
##                                   473                                   559 
##                               Somalia                          South Africa 
##                                   387                                   473 
##                           South Sudan                                 Spain 
##                                   344                                   430 
##                             Sri Lanka                    State of Palestine 
##                                   430                                   559 
##                                 Sudan                              Suriname 
##                                   473                                   473 
##                                Sweden                           Switzerland 
##                                   516                                   430 
##                  Syrian Arab Republic                            Tajikistan 
##                                   430                                   516 
##                              Thailand                           Timor-Leste 
##                                   516                                   516 
##                                  Togo                                 Tonga 
##                                   559                                   516 
##                   Trinidad and Tobago                               Tunisia 
##                                   473                                   516 
##                               Turkiye                          Turkmenistan 
##                                   516                                   559 
##                                Tuvalu                                Uganda 
##                                   559                                   559 
##                               Ukraine                  United Arab Emirates 
##                                   473                                   559 
##                        United Kingdom           United Republic of Tanzania 
##                                   473                                   516 
##                         United States                               Uruguay 
##                                   516                                   473 
##                            Uzbekistan                               Vanuatu 
##                                   559                                   516 
##    Venezuela (Bolivarian Republic of)                              Viet Nam 
##                                   602                                   473 
##                                  WCAR                                 Yemen 
##                                   441                                   516 
##                                Zambia                              Zimbabwe 
##                                   516                                   516
tabyl(data_long, country)
##                                country   n     percent
##                            Afghanistan 516 0.005006501
##                                Albania 559 0.005423709
##                                Algeria 516 0.005006501
##                                Andorra 473 0.004589292
##                                 Angola 559 0.005423709
##                    Antigua and Barbuda 430 0.004172084
##                              Argentina 602 0.005840917
##                                Armenia 559 0.005423709
##                              Australia 473 0.004589292
##                                Austria 473 0.004589292
##                             Azerbaijan 516 0.005006501
##                                Bahamas 473 0.004589292
##                                Bahrain 516 0.005006501
##                             Bangladesh 473 0.004589292
##                               Barbados 430 0.004172084
##                                Belarus 473 0.004589292
##                                Belgium 473 0.004589292
##                                 Belize 473 0.004589292
##                                  Benin 559 0.005423709
##                                 Bhutan 516 0.005006501
##       Bolivia (Plurinational State of) 559 0.005423709
##                 Bosnia and Herzegovina 430 0.004172084
##                               Botswana 559 0.005423709
##                                 Brazil 602 0.005840917
##                      Brunei Darussalam 473 0.004589292
##                               Bulgaria 559 0.005423709
##                           Burkina Faso 602 0.005840917
##                                Burundi 516 0.005006501
##                             Cabo Verde 473 0.004589292
##                               Cambodia 516 0.005006501
##                               Cameroon 559 0.005423709
##                                 Canada 473 0.004589292
##               Central African Republic 430 0.004172084
##                                   Chad 430 0.004172084
##                                  Chile 516 0.005006501
##                                  China 430 0.004172084
##                               Colombia 602 0.005840917
##                                Comoros 430 0.004172084
##                                  Congo 559 0.005423709
##                           Cook Islands 473 0.004589292
##                             Costa Rica 559 0.005423709
##                          Cote d'Ivoire 602 0.005840917
##                                Croatia 516 0.005006501
##                                   Cuba 473 0.004589292
##                                 Cyprus 430 0.004172084
##                                Czechia 430 0.004172084
##  Democratic People's Republic of Korea 430 0.004172084
##       Democratic Republic of the Congo 473 0.004589292
##                                Denmark 387 0.003754876
##                               Djibouti 516 0.005006501
##                               Dominica 473 0.004589292
##                     Dominican Republic 559 0.005423709
##                                   EAPR 415 0.004026546
##                                   ECAR 415 0.004026546
##                                   ESAR 441 0.004278812
##                                Ecuador 602 0.005840917
##                                  Egypt 473 0.004589292
##                            El Salvador 559 0.005423709
##                      Equatorial Guinea 430 0.004172084
##                                Eritrea 516 0.005006501
##                                Estonia 473 0.004589292
##                               Eswatini 516 0.005006501
##                               Ethiopia 473 0.004589292
##                                   Fiji 559 0.005423709
##                                Finland 473 0.004589292
##                                 France 473 0.004589292
##                                  Gabon 387 0.003754876
##                                 Gambia 602 0.005840917
##                                Georgia 559 0.005423709
##                                Germany 473 0.004589292
##                                  Ghana 559 0.005423709
##                                 Global 441 0.004278812
##                                 Greece 516 0.005006501
##                                Grenada 430 0.004172084
##                              Guatemala 559 0.005423709
##                                 Guinea 430 0.004172084
##                          Guinea-Bissau 516 0.005006501
##                                 Guyana 602 0.005840917
##                                  Haiti 516 0.005006501
##                               Honduras 559 0.005423709
##                                Hungary 430 0.004172084
##                                Iceland 387 0.003754876
##                                  India 559 0.005423709
##                              Indonesia 516 0.005006501
##             Iran (Islamic Republic of) 473 0.004589292
##                                   Iraq 559 0.005423709
##                                Ireland 473 0.004589292
##                                 Israel 559 0.005423709
##                                  Italy 473 0.004589292
##                                Jamaica 430 0.004172084
##                                  Japan 516 0.005006501
##                                 Jordan 473 0.004589292
##                             Kazakhstan 516 0.005006501
##                                  Kenya 559 0.005423709
##                               Kiribati 559 0.005423709
##                                 Kuwait 559 0.005423709
##                             Kyrgyzstan 559 0.005423709
##                                   LACR 441 0.004278812
##       Lao People's Democratic Republic 516 0.005006501
##                                 Latvia 559 0.005423709
##                                Lebanon 473 0.004589292
##                                Lesotho 516 0.005006501
##                                Liberia 516 0.005006501
##                                  Libya 516 0.005006501
##                              Lithuania 559 0.005423709
##                             Luxembourg 473 0.004589292
##                                   MENA 441 0.004278812
##                             Madagascar 473 0.004589292
##                                 Malawi 516 0.005006501
##                               Malaysia 516 0.005006501
##                               Maldives 473 0.004589292
##                                   Mali 516 0.005006501
##                                  Malta 473 0.004589292
##                       Marshall Islands 559 0.005423709
##                             Mauritania 473 0.004589292
##                              Mauritius 516 0.005006501
##                                 Mexico 559 0.005423709
##       Micronesia (Federated States of) 559 0.005423709
##                                 Monaco 430 0.004172084
##                               Mongolia 516 0.005006501
##                             Montenegro 430 0.004172084
##                                Morocco 559 0.005423709
##                             Mozambique 516 0.005006501
##                                Myanmar 559 0.005423709
##                                Namibia 559 0.005423709
##                                  Nauru 559 0.005423709
##                                  Nepal 516 0.005006501
##           Netherlands (Kingdom of the) 430 0.004172084
##                            New Zealand 473 0.004589292
##                              Nicaragua 516 0.005006501
##                                  Niger 516 0.005006501
##                                Nigeria 559 0.005423709
##                                   Niue 559 0.005423709
##                          Non-programme 415 0.004026546
##                        North Macedonia 559 0.005423709
##                                 Norway 473 0.004589292
##                                   Oman 516 0.005006501
##                               Pakistan 473 0.004589292
##                                  Palau 516 0.005006501
##                                 Panama 602 0.005840917
##                       Papua New Guinea 516 0.005006501
##                               Paraguay 559 0.005423709
##                                   Peru 602 0.005840917
##                            Philippines 559 0.005423709
##                                 Poland 516 0.005006501
##                               Portugal 516 0.005006501
##                                  Qatar 559 0.005423709
##                                   ROSA 415 0.004026546
##                      Republic of Korea 516 0.005006501
##                    Republic of Moldova 559 0.005423709
##                                Romania 516 0.005006501
##                     Russian Federation 473 0.004589292
##                                 Rwanda 516 0.005006501
##                  Saint Kitts and Nevis 473 0.004589292
##                            Saint Lucia 473 0.004589292
##       Saint Vincent and the Grenadines 473 0.004589292
##                                  Samoa 559 0.005423709
##                             San Marino 430 0.004172084
##                  Sao Tome and Principe 602 0.005840917
##                           Saudi Arabia 559 0.005423709
##                                Senegal 602 0.005840917
##                                 Serbia 516 0.005006501
##                             Seychelles 516 0.005006501
##                           Sierra Leone 559 0.005423709
##                              Singapore 516 0.005006501
##                               Slovakia 473 0.004589292
##                               Slovenia 473 0.004589292
##                        Solomon Islands 559 0.005423709
##                                Somalia 387 0.003754876
##                           South Africa 473 0.004589292
##                            South Sudan 344 0.003337667
##                                  Spain 430 0.004172084
##                              Sri Lanka 430 0.004172084
##                     State of Palestine 559 0.005423709
##                                  Sudan 473 0.004589292
##                               Suriname 473 0.004589292
##                                 Sweden 516 0.005006501
##                            Switzerland 430 0.004172084
##                   Syrian Arab Republic 430 0.004172084
##                             Tajikistan 516 0.005006501
##                               Thailand 516 0.005006501
##                            Timor-Leste 516 0.005006501
##                                   Togo 559 0.005423709
##                                  Tonga 516 0.005006501
##                    Trinidad and Tobago 473 0.004589292
##                                Tunisia 516 0.005006501
##                                Turkiye 516 0.005006501
##                           Turkmenistan 559 0.005423709
##                                 Tuvalu 559 0.005423709
##                                 Uganda 559 0.005423709
##                                Ukraine 473 0.004589292
##                   United Arab Emirates 559 0.005423709
##                         United Kingdom 473 0.004589292
##            United Republic of Tanzania 516 0.005006501
##                          United States 516 0.005006501
##                                Uruguay 473 0.004589292
##                             Uzbekistan 559 0.005423709
##                                Vanuatu 516 0.005006501
##     Venezuela (Bolivarian Republic of) 602 0.005840917
##                               Viet Nam 473 0.004589292
##                                   WCAR 441 0.004278812
##                                  Yemen 516 0.005006501
##                                 Zambia 516 0.005006501
##                               Zimbabwe 516 0.005006501

Dados faltantes

# Dados faltantes ----
skim(data_long) # Por que são faltantes? Precisamos deles?
Data summary
Name data_long
Number of rows 103066
Number of columns 6
_______________________
Column type frequency:
character 4
numeric 2
________________________
Group variables None

Variable type: character

skim_variable n_missing complete_rate min max empty n_unique whitespace
country 0 1.00 4 37 0 204 0
unicef_region 0 1.00 4 13 0 9 0
iso3 3865 0.96 3 3 0 195 0
vaccine 0 1.00 3 5 0 14 0

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
year 0 1.00 2001.12 12.41 1980 1990 2001 2012 2022 ▇▇▇▇▇
cov 39349 0.62 81.46 22.10 0 75 90 97 99 ▁▁▁▂▇
# Como são essas linhas?
data_long %>% 
  filter(!complete.cases(.)) %>% 
  view()

Padronizando tabela

Para trabalharmos de forma fácil com uma tabela, precisamos padronizá-la.

Isso significa que trocaremos e reordenaremos os nomes das colunas para fazerem mais sentido, completaremos os valores NA quando for possível (e fizer sentido), e explicitaremos algumas coisas, como o nome das doenças contra as quais as vacinas protegem, e daremos o nome completo de cada região, pois somente temos os códigos delas.

No caso dos valores NA, sabemos que certas vacinas não estavam disponíveis para todos os países ao mesmo tempo. Por isso, deixaremos como NA e não trocaremos por 0. Valores faltantes são diferentes de 0, por mais que em muitos casos possam ser trocados.

Dessa forma, utilizaremos o if_else(). Nele, estabelecemos que, se a coluna name for igual à region, então o type será “region”, caso contrário, será “country”. Completaremos o mesmo com a coluna de abreviação

Além disso, na tabela original, temos dados para todos os países e continentes. Ou seja, temos uma linha chamada “Brasil” e outra chamada “Latin America”, por exemplo. Sabemos que o último não é um país, então criaremos uma coluna chamada type usando o if_else() para diferenciar quando quisermos trabalhar com cada tipo.

Para dar os nomes completos das regiões e criar uma coluna das doenças relacionadas às vacinas, usamos o case_when(), que é um if_else() que aceita mais relações.

Assim, quando algo for igual a algo, chame ele de algo, se algo 2 for igual a algo 2, chame ele de algo 2, … e se isso tudo for mentira, então deixe como está.

# Padronizando a tabela ----

data_long_standardized = data_long %>% 
  select(name = country, 
         country_abrev = iso3, 
         year, 
         vaccine, 
         coverage = cov, 
         region = unicef_region) %>% 
  
  
  
  mutate(
         # Anotando dados
         year = as.integer(year), #Aqui, converteremos year em número inteiro, para evitar que seja lido com decimais.
         type = if_else(name == region, # Se o nome for igual à região,
                        "region",       # então ele é uma região,
                        "country"),     # caso contrário, é um país.
         
         country_abrev = if_else(name == region, # Se o nome for igual à região,
                        name,       # então ele é uma região,
                        country_abrev),     # caso contrário, é um país.
         
         region = if_else(is.na(region), 
                          name, 
                          region),
         
         # Vacinas por doenças
         diseases = case_when(vaccine == "BCG" ~ "Tuberculosis",
                              vaccine == "DTP1" ~ "Difteria, Tetanus, Pertussis",
                              vaccine == "DT3" ~ "Difteria, Tetanus, Pertussis",
                              vaccine == "HEPB3" ~ "Hepatitis B",
                              vaccine == "HEPBB" ~ "Hepatitis B",
                              vaccine == "HIB3" ~ "Haemophilus influenzae B",
                              vaccine == "IPV1" ~ "Poliomielitis",
                              vaccine == "MCV1" ~ "Measles",
                              vaccine == "MCV2" ~ "Measles",
                              vaccine == "PCV3" ~ "Pneumococcus",
                              vaccine == "POL3" ~ "Poliomielitis",
                              vaccine == "RCV1" ~ "Rotavirus",
                              vaccine == "ROTAC" ~ "Rotavirus",
                              vaccine == "YFV" ~ "Yellow fever",
                              TRUE ~ vaccine
                              ),
         
         
         # Abreviação para nome completo
         region_complete = case_when(region == "EAPR" ~ "East Asia and Pacific", 
                              region == "ECAR" ~ "Europe and Central Asia",
                              region == "MENA" ~ "Middle East and North Africa",
                              region == "ESAR" ~ "Eastern and Southern Africa",
                              region == "LACR" ~ "Latin America and Caribbean",
                              region == "Non-programme" ~ "Non-programme",
                              region == "ROSA" ~ "South Asia",
                              region == "WCAR" ~ "West and Central Africa",
                              TRUE ~ region
  ))

#Salvar tabela
data_long_standardized %>% 
  saveRDS(file = "cobertura_vacinal_unicef_padronizada.rds")

#Tabela larga
data_wide = data_long_standardized %>% 
   pivot_wider(names_from = year, 
               values_from = coverage)

Unindo tabelas

#Tabela com vacinação
data_long_standardized = readRDS(file = "cobertura_vacinal_unicef_padronizada.rds")
data_long_standardized
## # A tibble: 103,066 × 9
##    name        country_abrev  year vaccine coverage region type    diseases    
##    <chr>       <chr>         <int> <chr>      <dbl> <chr>  <chr>   <chr>       
##  1 Afghanistan AFG            2022 BCG           88 ROSA   country Tuberculosis
##  2 Afghanistan AFG            2021 BCG           84 ROSA   country Tuberculosis
##  3 Afghanistan AFG            2020 BCG           87 ROSA   country Tuberculosis
##  4 Afghanistan AFG            2019 BCG           86 ROSA   country Tuberculosis
##  5 Afghanistan AFG            2018 BCG           89 ROSA   country Tuberculosis
##  6 Afghanistan AFG            2017 BCG           84 ROSA   country Tuberculosis
##  7 Afghanistan AFG            2016 BCG           78 ROSA   country Tuberculosis
##  8 Afghanistan AFG            2015 BCG           76 ROSA   country Tuberculosis
##  9 Afghanistan AFG            2014 BCG           74 ROSA   country Tuberculosis
## 10 Afghanistan AFG            2013 BCG           72 ROSA   country Tuberculosis
## # ℹ 103,056 more rows
## # ℹ 1 more variable: region_complete <chr>
#Tabela com dados gerais de paises
paises_anotados = readRDS(file = "paises_anotados.rds")
paises_anotados
## # A tibble: 204 × 3
## # Groups:   name [204]
##    name                   continent region_complete             
##    <chr>                  <chr>     <chr>                       
##  1 Afghanistan            Asia      South Asia                  
##  2 Albania                Europe    Europe and Central Asia     
##  3 Algeria                Africa    Middle East and North Africa
##  4 Angola                 Africa    Eastern and Southern Africa 
##  5 Argentina              Americas  Latin America and Caribbean 
##  6 Austria                Europe    Non-programme               
##  7 Bangladesh             Asia      South Asia                  
##  8 Benin                  Africa    West and Central Africa     
##  9 Bosnia and Herzegovina Europe    Europe and Central Asia     
## 10 Botswana               Africa    Eastern and Southern Africa 
## # ℹ 194 more rows
#Unindo tabelas
data_long_annotated = data_long_standardized %>% 
  inner_join(paises_anotados, by = "name")

glimpse(data_long_annotated) #Colunas duplicadas
## Rows: 103,066
## Columns: 11
## $ name              <chr> "Afghanistan", "Afghanistan", "Afghanistan", "Afghan…
## $ country_abrev     <chr> "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AF…
## $ year              <int> 2022, 2021, 2020, 2019, 2018, 2017, 2016, 2015, 2014…
## $ vaccine           <chr> "BCG", "BCG", "BCG", "BCG", "BCG", "BCG", "BCG", "BC…
## $ coverage          <dbl> 88, 84, 87, 86, 89, 84, 78, 76, 74, 72, 78, 71, 68, …
## $ region            <chr> "ROSA", "ROSA", "ROSA", "ROSA", "ROSA", "ROSA", "ROS…
## $ type              <chr> "country", "country", "country", "country", "country…
## $ diseases          <chr> "Tuberculosis", "Tuberculosis", "Tuberculosis", "Tub…
## $ region_complete.x <chr> "South Asia", "South Asia", "South Asia", "South Asi…
## $ continent         <chr> "Asia", "Asia", "Asia", "Asia", "Asia", "Asia", "Asi…
## $ region_complete.y <chr> "South Asia", "South Asia", "South Asia", "South Asi…
data_long_annotated = data_long_standardized %>% 
  inner_join(paises_anotados %>% 
               select(-region_complete), by = "name")

glimpse(data_long_annotated)
## Rows: 103,066
## Columns: 10
## $ name            <chr> "Afghanistan", "Afghanistan", "Afghanistan", "Afghanis…
## $ country_abrev   <chr> "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG"…
## $ year            <int> 2022, 2021, 2020, 2019, 2018, 2017, 2016, 2015, 2014, …
## $ vaccine         <chr> "BCG", "BCG", "BCG", "BCG", "BCG", "BCG", "BCG", "BCG"…
## $ coverage        <dbl> 88, 84, 87, 86, 89, 84, 78, 76, 74, 72, 78, 71, 68, 64…
## $ region          <chr> "ROSA", "ROSA", "ROSA", "ROSA", "ROSA", "ROSA", "ROSA"…
## $ type            <chr> "country", "country", "country", "country", "country",…
## $ diseases        <chr> "Tuberculosis", "Tuberculosis", "Tuberculosis", "Tuber…
## $ region_complete <chr> "South Asia", "South Asia", "South Asia", "South Asia"…
## $ continent       <chr> "Asia", "Asia", "Asia", "Asia", "Asia", "Asia", "Asia"…
#Tabela com mortes por doenças imunopreníveis, por país, ano, sexo e idade
Deaths_infectious_diseases = readRDS(file = "Deaths_infectious_diseases.rds")
glimpse(Deaths_infectious_diseases) # mais de 2 milhões de linhas
## Rows: 2,719,521
## Columns: 12
## $ who_region_name                         <chr> "Europe", "Europe", "Europe", …
## $ who_region_code                         <chr> "EU", "EU", "EU", "EU", "EU", …
## $ name                                    <chr> "Albania", "Albania", "Albania…
## $ country_abrev                           <chr> "ALB", "ALB", "ALB", "ALB", "A…
## $ sex                                     <chr> "All", "All", "All", "All", "A…
## $ year                                    <dbl> 1987, 1987, 1987, 1987, 1987, …
## $ age                                     <chr> "[All]", "[0]", "[1-4]", "[5-9…
## $ total_deaths                            <dbl> 69, 21, 14, 4, 0, 3, 5, 6, 2, …
## $ perc_deaths                             <dbl> 0.39824541, 0.85400569, 1.1336…
## $ death_rate_100thousand                  <dbl> 2.2431000, 26.0545906, 4.89510…
## $ death_rate_100thousand_age_standardized <dbl> 2.050773, NA, NA, NA, NA, NA, …
## $ death_disease                           <chr> "Hepatitis B", "Hepatitis B", …
#Reduzir tabela
Deaths_infectious_diseases_filtered = Deaths_infectious_diseases %>% 
  filter(age == "[All]",
         sex == "All") %>%  # 904 mil linhas
  select(name, year, total_deaths:death_disease) 

#Quais colunas são iguais e têm nomes diferentes?
glimpse(data_long_standardized)
## Rows: 103,066
## Columns: 9
## $ name            <chr> "Afghanistan", "Afghanistan", "Afghanistan", "Afghanis…
## $ country_abrev   <chr> "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG"…
## $ year            <int> 2022, 2021, 2020, 2019, 2018, 2017, 2016, 2015, 2014, …
## $ vaccine         <chr> "BCG", "BCG", "BCG", "BCG", "BCG", "BCG", "BCG", "BCG"…
## $ coverage        <dbl> 88, 84, 87, 86, 89, 84, 78, 76, 74, 72, 78, 71, 68, 64…
## $ region          <chr> "ROSA", "ROSA", "ROSA", "ROSA", "ROSA", "ROSA", "ROSA"…
## $ type            <chr> "country", "country", "country", "country", "country",…
## $ diseases        <chr> "Tuberculosis", "Tuberculosis", "Tuberculosis", "Tuber…
## $ region_complete <chr> "South Asia", "South Asia", "South Asia", "South Asia"…
glimpse(Deaths_infectious_diseases_filtered)
## Rows: 43,076
## Columns: 7
## $ name                                    <chr> "Albania", "Albania", "Albania…
## $ year                                    <dbl> 1987, 1988, 1989, 1992, 1993, …
## $ total_deaths                            <dbl> 69, 58, 50, 24, 27, 19, 17, 6,…
## $ perc_deaths                             <dbl> 0.39824541, 0.33578417, 0.2751…
## $ death_rate_100thousand                  <dbl> 2.24310003, 1.84825213, 1.5711…
## $ death_rate_100thousand_age_standardized <dbl> 2.05077307, 1.74589545, 1.4595…
## $ death_disease                           <chr> "Hepatitis B", "Hepatitis B", …
#Unir tabelas
data_long_annotated = data_long_annotated %>% 
    rename(disease_vac = diseases) %>% 
  left_join(Deaths_infectious_diseases_filtered,
             #by = "name") #Unir por uma coluna
             
             by = join_by(name, #Unir por mais colunas
                          year,
                          disease_vac == death_disease
                          ))

glimpse(data_long_annotated)
## Rows: 103,066
## Columns: 14
## $ name                                    <chr> "Afghanistan", "Afghanistan", …
## $ country_abrev                           <chr> "AFG", "AFG", "AFG", "AFG", "A…
## $ year                                    <dbl> 2022, 2021, 2020, 2019, 2018, …
## $ vaccine                                 <chr> "BCG", "BCG", "BCG", "BCG", "B…
## $ coverage                                <dbl> 88, 84, 87, 86, 89, 84, 78, 76…
## $ region                                  <chr> "ROSA", "ROSA", "ROSA", "ROSA"…
## $ type                                    <chr> "country", "country", "country…
## $ disease_vac                             <chr> "Tuberculosis", "Tuberculosis"…
## $ region_complete                         <chr> "South Asia", "South Asia", "S…
## $ continent                               <chr> "Asia", "Asia", "Asia", "Asia"…
## $ total_deaths                            <dbl> NA, NA, NA, NA, NA, NA, NA, NA…
## $ perc_deaths                             <dbl> NA, NA, NA, NA, NA, NA, NA, NA…
## $ death_rate_100thousand                  <dbl> NA, NA, NA, NA, NA, NA, NA, NA…
## $ death_rate_100thousand_age_standardized <dbl> NA, NA, NA, NA, NA, NA, NA, NA…

Organizar colunas

#Organizar colunas
data_long_annotated = data_long_annotated %>% 
  select(type, name, country_abrev, continent, region, region_complete, year, everything())

#Salvar
data_long_annotated %>% 
  saveRDS(file = "cobertura_vacinal_anotada.rds")

Estatísticas descritivas

Abaixo, queremos obter o resumo dos dados de cada país na região da América latina. Como a tabela tem linhas com dados faltantes, algumas operações podem confundir os resultados. Por isso, usamos a função drop_na().

Além disso, queremos filtrar somente os dados dos países latinoamericanos entre os anos 2000 e 2023. Para isso, usamos o between() dentro da função filter(), e especificamos que queremos o type == “country”, pois também temos dados da região como um todo.

Como não queremos trabalhar com os nomes completos das regiões, podemos ser menos específicos. Por exemplo, se sabemos que existe a região “Latin America and Caribbean Region (LACR)”, podemos somente usar uma função que pega um pedaço do nome completo e nos retorna aquela linha. Isso é feito com o str_detect().

Para calcularmos as estatísticas gerais com summarize, precisamos agrupar os dados com group_by. Isso porque temos dados da cobertura vacinal por país em 23 anos e para mais de uma vacina. Dessa forma, agruparemos por país (name) e vacina (vaccine). Ao final, vamos desagrupar esses dados.

Por país

# Estatísticas de cada país em um continente
# Média, mediana, mínimo e máximo de uma variável numérica

latin_2000_2023 = data_long_annotated %>% 
  
  #Missing values: Aqui, é importante retirá-los para não repetir linhas
  
  drop_na(coverage) %>% 
   
  filter(between(year, 2000, 2023),
         str_detect(region_complete, "Latin"),
         type == "country") %>% 
  
  #Agrupar por vacina e país
  group_by(vaccine, name) %>% 
  
  #Resumir estatísticas
  summarise(
    mean = mean(coverage),
    median = median(coverage),
    max = max(coverage),
    min = min(coverage),
    sd = sd(coverage),
    var = var(coverage)
  ) %>% 
  
  #Desagrupar
  ungroup()
## `summarise()` has grouped output by 'vaccine'. You can override using the
## `.groups` argument.
latin_2000_2023
## # A tibble: 402 × 8
##    vaccine name                              mean median   max   min    sd   var
##    <chr>   <chr>                            <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl>
##  1 BCG     Argentina                         94.1     99    99    75  7.32 53.6 
##  2 BCG     Belize                            95.5     98    99    76  5.55 30.8 
##  3 BCG     Bolivia (Plurinational State of)  90.4     92    99    76  6.67 44.5 
##  4 BCG     Brazil                            95.1     99    99    69  8.46 71.6 
##  5 BCG     Chile                             96.1     96    99    91  2.28  5.21
##  6 BCG     Colombia                          89.8     89    97    84  3.29 10.8 
##  7 BCG     Costa Rica                        95.2     96    99    88  3.86 14.9 
##  8 BCG     Cuba                              99       99    99    99  0     0   
##  9 BCG     Dominica                          97.2     98    99    89  2.81  7.88
## 10 BCG     Dominican Republic                96.5     98    99    85  3.65 13.4 
## # ℹ 392 more rows

Por continente Aqui, faremos o mesmo, mas para cada continente.

# Cobertura vacinal: Estatísticas de cada continente
continentes_vac = data_long_annotated %>% 
  drop_na(coverage,
          continent) %>% 
  filter(between(year, 2000, 2023),
         type == "country") %>% 
  group_by(vaccine, continent) %>% 
  summarise(
    mean = mean(coverage),
    median = median(coverage),
    max = max(coverage),
    min = min(coverage),
    sd = sd(coverage),
    var = var(coverage)
  ) %>% 
  ungroup()
## `summarise()` has grouped output by 'vaccine'. You can override using the
## `.groups` argument.
#Visualizar
continentes_vac
## # A tibble: 79 × 8
##    vaccine continent  mean median   max   min    sd    var
##    <chr>   <chr>     <dbl>  <dbl> <dbl> <dbl> <dbl>  <dbl>
##  1 BCG     Africa     85.4     90    99    26 14.5  211.  
##  2 BCG     Americas   93.6     96    99    28  7.36  54.2 
##  3 BCG     Asia       91.7     96    99    29 10.8  117.  
##  4 BCG     Europe     86.7     97    99    16 23.6  557.  
##  5 BCG     Other      92.3     96    99     0 10.4  109.  
##  6 DTP1    Africa     85.3     91    99    35 14.1  198.  
##  7 DTP1    Americas   94.3     96    99    73  5.50  30.2 
##  8 DTP1    Asia       92.4     96    99    45  8.95  80.0 
##  9 DTP1    Europe     97.2     98    99    84  2.34   5.47
## 10 DTP1    Oceania    94.8     95    98    90  2.50   6.25
## # ℹ 69 more rows

Mortes cumulativas

Por continente

# Mortes cumulativas
# Estatísticas de cada continente
continentes_mortes = data_long_annotated %>% 
  
  drop_na(total_deaths,
          continent) %>%
  
  filter(between(year, 2000, 2023),
         type == "country") %>% 
  
  group_by(disease_vac, continent) %>%
  
  summarise(
    cumulativo = sum(total_deaths),
    mean = mean(total_deaths),
    median = median(total_deaths),
    max = max(total_deaths),
    min = min(total_deaths),
    sd = sd(total_deaths),
    var = var(total_deaths)
  ) %>% 
  
  #Aqui, queremos os países com maior número de mortes
  arrange(disease_vac, - cumulativo) %>% 
  ungroup()
## `summarise()` has grouped output by 'disease_vac'. You can override using the
## `.groups` argument.
continentes_mortes
## # A tibble: 17 × 9
##    disease_vac  continent cumulativo     mean median   max   min      sd     var
##    <chr>        <chr>          <dbl>    <dbl>  <dbl> <dbl> <dbl>   <dbl>   <dbl>
##  1 Hepatitis B  Africa        210404  2.57e+3    392  7771     0 2.89e+3 8.37e+6
##  2 Hepatitis B  Other          87412  7.10e+1      4  2262     0 2.21e+2 4.90e+4
##  3 Hepatitis B  Americas       70991  1.08e+2     33   942     0 2.05e+2 4.21e+4
##  4 Hepatitis B  Asia           69672  1.93e+2     20  1352     0 3.11e+2 9.65e+4
##  5 Hepatitis B  Europe         36195  6.60e+1     27  1948     0 1.42e+2 2.03e+4
##  6 Hepatitis B  Oceania          767  1.97e+1     13    55     3 1.36e+1 1.86e+2
##  7 Measles      Asia           16976  4.16e+1      0  1787     0 2.27e+2 5.13e+4
##  8 Measles      Africa          1860  1.5 e+1      7   206     0 2.85e+1 8.13e+2
##  9 Measles      Other            538  3.63e-1      0    21     0 1.62e+0 2.63e+0
## 10 Measles      Europe           526  5.36e-1      0    14     0 1.58e+0 2.49e+0
## 11 Measles      Americas         236  3.07e-1      0    15     0 1.58e+0 2.50e+0
## 12 Measles      Oceania            8  1.03e-1      0     1     0 3.05e-1 9.32e-2
## 13 Tuberculosis Africa       1052032  1.70e+4    478 77589     6 2.71e+4 7.33e+8
## 14 Tuberculosis Other         800245  1.31e+3     67 32220     0 4.30e+3 1.85e+7
## 15 Tuberculosis Asia          601739  3.24e+3    555 28507     6 6.84e+3 4.68e+7
## 16 Tuberculosis Americas      290414  8.35e+2    306  6000     4 1.30e+3 1.69e+6
## 17 Tuberculosis Europe         83333  2.51e+2     75  2387     1 4.10e+2 1.68e+5

Por país

# Mortes cumulativas
# Estatísticas de cada continente
paises_mortes = data_long_annotated %>% 
  drop_na(total_deaths,
          name) %>% 
  filter(between(year, 2000, 2023),
         type == "country") %>% 
  group_by(disease_vac, name) %>% 
  summarise(
    cumulativo = sum(total_deaths),
    mean = mean(total_deaths),
    median = median(total_deaths),
    max = max(total_deaths),
    min = min(total_deaths),
    sd = sd(total_deaths),
    var = var(total_deaths)
  ) %>% 
  arrange(disease_vac, desc(cumulativo)) %>% 
  ungroup()
## `summarise()` has grouped output by 'disease_vac'. You can override using the
## `.groups` argument.
paises_mortes
## # A tibble: 296 × 9
##    disease_vac name            cumulativo  mean median   max   min     sd    var
##    <chr>       <chr>                <dbl> <dbl>  <dbl> <dbl> <dbl>  <dbl>  <dbl>
##  1 Hepatitis B Egypt               204890 5122.  5602.  7771  1563 2070.  4.28e6
##  2 Hepatitis B Brazil               33536  798.   781    942   693   68.2 4.65e3
##  3 Hepatitis B Russian Federa…      26997 1350.  1254.  2262   778  471.  2.22e5
##  4 Hepatitis B Republic of Ko…      26368  599.   572    869   349  173.  2.98e4
##  5 Hepatitis B Philippines          23446  782.   743   1037   632  115.  1.32e4
##  6 Hepatitis B Japan                19331  879.   844   1352   507  284.  8.06e4
##  7 Hepatitis B Mexico               17108  389.   372    586   230  103.  1.07e4
##  8 Hepatitis B Thailand             16792  442.   366    983   179  243.  5.89e4
##  9 Hepatitis B Italy                10577  504.   338   1948   236  482.  2.32e5
## 10 Hepatitis B Iran (Islamic …       6886  689.   610    870   547  133.  1.78e4
## # ℹ 286 more rows

5. Visualização

Vacinação

Gráfico de pontos simples

Por continente

#Gráfico de pontos simples
continentes_pontos_vac = continentes_vac %>% #Dataframe
  filter(vaccine %in% "MCV1") %>%
  mutate(continent = fct_reorder(continent, median)) %>% 
  ggplot() + #Chamando a função. Aqui se usa "+" em vez de "%>%" 
  
  #Mapeando os eixos
  aes(x = median,
      y = continent,
      color = continent) +
  
  #Geometrias
  geom_point() +
  
  geom_label(aes(x = median, 
                y = continent, 
                label = median)) +
  
  #Tema
  theme_light() +
  
  #Labels
  labs(title = "Cobertura vacinal",
       x = "Mediana (Cobertura vacinal %)",
       y = "Continentes") 

continentes_pontos_vac

Por país

#Gráfico de pontos simples
pontos = latin_2000_2023 %>% #Dataframe
  filter(vaccine %in% "MCV1") %>%
  ggplot() + #Chamando a função. Aqui se usa "+" em vez de "%>%" 
  
  #Mapeando os eixos
  aes(x = median,
      y = name,
      color = median) +
  
  #Geometrias
  geom_point() +
  
  geom_text(aes(x = median, #Use geom_label para visualizar melhor
                y = name, 
                label = median)) +
  
  #Tema
  theme_light() +
  
  #Labels
  labs(title = "Cobertura vacinal",
       x = "Mediana (Cobertura vacinal%)",
       y = "Países")

pontos

Gráfico de barras

Por continente

#Gráfico de barras simples
continente_barras_vac = continentes_vac %>% #Dataframe
  filter(vaccine %in% "MCV1") %>%
  mutate(continent = fct_reorder(continent, median)) %>% 
  ggplot() + #Chamando a função. Aqui se usa "+" em vez de "%>%" 
  
  #Mapeando os eixos
  aes(x = median,
      y = continent,
      fill = continent) +
  
  #Geometrias
  geom_col() +
  
  geom_text(aes(x = median, 
                y = continent, 
                label = median)) +
  
  #Tema
  theme_light() +
  
  #Labels
  labs(title = "Cobertura vacinal",
       x = "Mediana (Cobertura vacinal %)",
       y = "Continentes") 

continente_barras_vac

Por país

#Gráfico de barras simples
pais_barras_vac = latin_2000_2023 %>% #Dataframe
  filter(vaccine %in% "MCV1") %>%
  ggplot() + #Chamando a função. Aqui se usa "+" em vez de "%>%" 
  
  #Mapeando os eixos
  aes(x = median,
      y = name,
      fill = median) +
  
  #Geometrias
  geom_col() +
  
  geom_text(aes(x = median, 
                y = name, 
                label = median)) +
  
  #Tema
  theme_light() +
  
  #Labels
  labs(title = "Título",
       x = "Mediana (Cobertura vacinal%)",
       y = "Países")

pais_barras_vac

Mortes

Por continente

#Gráfico de pontos simples
barras_mortes = continentes_mortes %>% #Dataframe
  filter(disease_vac == "Measles") %>% 
  mutate(continent = fct_reorder(continent, cumulativo)) %>% 
  ggplot() + #Chamando a função. Aqui se usa "+" em vez de "%>%" 
  
  #Mapeando os eixos
  aes(x = cumulativo,
      y = continent,
      fill = continent) +
  
  #Geometrias
  geom_col() +
  
  geom_label(aes(x = cumulativo, 
                y = continent, 
                label = cumulativo),
            hjust = -0.2) +
  
  #Tema
  theme_light() +
  
  #Labels
  labs(title = "Mortes cumulativas por Sarampo, de 2000 a 2023",
       x = "Mortes",
       y = "Continentes") +
  
  #Eixo x
  xlim(0, 21000) #Aumentar limites 
  
barras_mortes 

#Gráfico de pontos simples
paises_barras_mortes = paises_mortes %>% #Dataframe
  filter(disease_vac == "Measles") %>% 
  mutate(name = fct_reorder(name, cumulativo)) %>% 
  slice_max(order_by = cumulativo, n = 10) %>% 
  ggplot() + #Chamando a função. Aqui se usa "+" em vez de "%>%" 
  
  #Mapeando os eixos
  aes(x = cumulativo,
      y = name,
      fill = name) +
  
  #Geometrias
  geom_col() +
  
  geom_label(aes(x = cumulativo, 
                y = name, 
                label = cumulativo),
            hjust = -0.2) +
  
  #Tema
  theme_light() +
  
  #Labels
  labs(title = "Mortes cumulativas por Sarampo, de 2000 a 2023",
       x = "Mortes",
       y = "Continentes") +
  
  #Eixo x
  xlim(0, 21000) #Aumentar limites 
  
paises_barras_mortes

Visualização rápida com o Esquisse

#Visualização rápida
# latin_2000_2023 %>% 
#   esquisser() 

Melhorando o gráfico

# Melhorando o gráfico -----

plot = 
  
  # Manipular tabela
  latin_2000_2023 %>%
  filter(vaccine %in% "MCV1") %>%
  mutate(name = fct_reorder(name, median)) %>% 
 
  #Criar base do gráfico
  ggplot() +
  aes(x = median, y = name, colour = median) + #Aesthetics (mapping)
  
  #Geometria
  geom_point(shape = "circle", 
             size = 1) +
  #Highlight (add sempre após geom_)
  gghighlight(median >= 95,
              label_key = name,
              label_params = list(size = 3),
              unhighlighted_params = list(colour = "red")) +
  
  #Labels
  geom_text(aes(x = median, 
                y = name, 
                label = median),
              hjust = -0.5,
              size = 3,
              color = "black") +
  
  #Marcações
  #Linhas
  geom_vline(xintercept = 95,
             colour = "black",
             size =0.2,
             linetype = 2) +
  
  #Tema, aparência
  theme_light() + 
  
  # Labels, titulo, subtitulo, titulo dos eixos
    
  labs(title = "Vacinação em países da América Latina",
     subtitle = "Sarampo, MCV1, Dose 1, entre 2000 e 2023",
     y = "Países",
     x = "Mediana (Cobertura %)",
     tag = "Figure A.",
     colour = "Cobertura vacinal",
     caption = "Fonte: Feito pela UPVacina") +
  
  # Aparência especifica
  theme(
    
    #Texto geral
    text = element_text(family = "sans",  #sans, mono, serif
                        color = "black"), 
    
    #Título, subtítulo e tag
    plot.title = element_text(size = 12, 
                              face = "bold", 
                              hjust = 0,
                              vjust = 0.5),
    plot.subtitle = element_text(size = 10),
    plot.tag.position = "topleft",
    plot.tag = element_text(vjust = 5,
                            size = 12, 
                            face = "bold"),
    
    #Legenda
    legend.title = element_text(face = "bold"),
    legend.text = element_text(size = 10),
    
    #Eixos
    axis.title.x = element_text(size = 10,
                                angle = 0,
                                color = "black"),
    axis.text.x = element_text(color = "black",
                               size = 8,
                               angle = 0),
    axis.text.y = element_text(size = 8,
                               color = "black"),
    
    #Margens do gráfico
    plot.margin = unit(c(0.5, #Top
                         1, #Right
                         0.5, #Bottom
                         0), #Left 
                       "cm") #Unidade) 
  ) 
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
  #Escala de cores
  # scale_colour_manual(low = "#DC0000B2", 
  #                       high = "#4DBBD5B2",
  #                       breaks = c(90, 100)) +
  # scale_colour_steps(low = "#DC0000B2", 
  #                       high = "#4DBBD5B2")


#Visualizar
plot

#Salvar
ggsave(plot, file = "Sarampo_LatinAmerica_2000_2023.png", width = 10, height = 5)

Gráfico interativo

plot %>% 
  ggplotly() 
## Warning in geom2trace.default(dots[[1L]][[5L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomLabelRepel() has yet to be implemented in plotly.
##   If you'd like to see this geom implemented,
##   Please open an issue with your example code at
##   https://github.com/ropensci/plotly/issues

## Warning in geom2trace.default(dots[[1L]][[5L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomLabelRepel() has yet to be implemented in plotly.
##   If you'd like to see this geom implemented,
##   Please open an issue with your example code at
##   https://github.com/ropensci/plotly/issues

## Warning in geom2trace.default(dots[[1L]][[5L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomLabelRepel() has yet to be implemented in plotly.
##   If you'd like to see this geom implemented,
##   Please open an issue with your example code at
##   https://github.com/ropensci/plotly/issues

## Warning in geom2trace.default(dots[[1L]][[5L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomLabelRepel() has yet to be implemented in plotly.
##   If you'd like to see this geom implemented,
##   Please open an issue with your example code at
##   https://github.com/ropensci/plotly/issues

## Warning in geom2trace.default(dots[[1L]][[5L]], dots[[2L]][[1L]], dots[[3L]][[1L]]): geom_GeomLabelRepel() has yet to be implemented in plotly.
##   If you'd like to see this geom implemented,
##   Please open an issue with your example code at
##   https://github.com/ropensci/plotly/issues

Unindo gráficos

#Unindo gráficos -----

vaccination = data_long_annotated %>% 
  filter(name == "Brazil",
         vaccine == "MCV1") %>% 
    ggplot() +
  geom_line(mapping = aes(
    x = year,
    y = coverage),
    colour = "#4DBBD5B2",
    linewidth = 2) +
    geom_text(aes(x = year, 
                  y = coverage, 
                  label = coverage),
            vjust = -0.5,
            size = 2) +
    theme_minimal() +
  labs(title = "Cobertura vacinal contra o sarampo, Brasil",
       x = "Ano",
       y = "Cobertura vacinal (%)") +
   ylim(0, 110)

vaccination

#Mortes
deaths = data_long_annotated %>% 
  filter(name == "Brazil",
         vaccine == "MCV1") %>% 
    ggplot() +
  aes(x = year, y = total_deaths) +
  geom_col(fill = "#DC0000B2") +
  geom_text(aes(label = total_deaths),
            vjust = -0.5,
            size = 2) +
  theme_minimal() +
  theme(text = element_text(size = 10)) +
    labs(title = "Mortes por sarampo, Brasil",
       x = "Ano",
       y = "Mortes") +
   ylim(0, 3400)

deaths
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_col()`).
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_text()`).

Unindo gráficos em uma imagem

#Unir gráficos
(vaccination / deaths) 
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_col()`).
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_text()`).

(vaccination + deaths) 
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_col()`).
## Removed 2 rows containing missing values or values outside the scale range
## (`geom_text()`).

#Salvar
(vaccination / deaths) %>% 
  ggsave(file = "Sarampo_Brasil_1980_2023.png", width = 10, height = 5)
## Warning: Removed 2 rows containing missing values or values outside the scale range
## (`geom_col()`).
## Removed 2 rows containing missing values or values outside the scale range
## (`geom_text()`).

Boxplots

#Boxplot simples por ano
boxplot_years = data_long_annotated %>% 
  filter(type == "country",
         vaccine == "MCV1",
         year %in% c(1990, 2000, 2010, 2019)) %>% 
  
  
 ggplot() +
  aes(x = "", 
      y = coverage, 
      fill = continent) +
  geom_boxplot() +
  scale_fill_brewer(palette = "Set2", direction = 1) +
  theme_bw() + 
  theme(axis.text.x = element_text(angle = 45,
                                   vjust = 1,
                                   hjust = 1),
        plot.margin = unit(c(1, 1, 1, 1), "cm"),
        legend.position = "right") +
  facet_wrap(vars(year), ncol = 4) +
  labs(title = "Cobertura vacinal contra o sarampo",
       subtitle = "Primeira dose (MCV1)",
      x = "Região UNICEF",
       y = "Cobertura vacinal (%)",
       fill = "Região UNICEF")

#Visualizar
boxplot_years 
## Warning: Removed 37 rows containing non-finite outside the scale range
## (`stat_boxplot()`).

Paleta de cores científica

# Cores
#Mudando a paleta
library(ggsci)
library(scales)
## Warning: package 'scales' was built under R version 4.3.2
## 
## Attaching package: 'scales'
## The following object is masked from 'package:purrr':
## 
##     discard
## The following object is masked from 'package:readr':
## 
##     col_factor
vignette("ggsci") 

nrc = pal_npg("nrc", #Especificar paleta
              alpha = 0.7)(8) #Gerar 10 cores com transparencia = 70%

nrc %>% 
  show_col()

boxplot_years + scale_fill_npg()
## Scale for fill is already present.
## Adding another scale for fill, which will replace the existing scale.
## Warning: Removed 37 rows containing non-finite outside the scale range
## (`stat_boxplot()`).

#Boxplot simples de ano
boxplot_regions = data_long_annotated %>% 
  filter(type == "country",
         vaccine == "MCV1",
         year %in% c(1990, 2000, 2010, 2020)) %>% 
  mutate(year = as.factor(year)) %>% 
 ggplot() +
  aes(x = year, y = coverage, fill = year) +
  geom_boxplot() +
  geom_jitter(aes(label = name),
              alpha = 0.2,
              na.rm = T) +
  scale_fill_brewer(palette = "Set2", direction = 1) +
  scale_color_distiller(palette = "Set2", direction = 1) +
  theme_minimal() +
  facet_wrap(vars(continent)) +
  scale_fill_npg()
## Warning in geom_jitter(aes(label = name), alpha = 0.2, na.rm = T): Ignoring
## unknown aesthetics: label
## Scale for fill is already present.
## Adding another scale for fill, which will replace the existing scale.
boxplot_regions
## Warning: Removed 37 rows containing non-finite outside the scale range
## (`stat_boxplot()`).

# Gráfico interativo
boxplot_regions %>%  
  ggplotly()
## Warning: Removed 37 rows containing non-finite outside the scale range
## (`stat_boxplot()`).
#Boxplot por vacina
data_long_annotated %>% 
  filter(type == "country",
         year == 2015) %>% 
 ggplot() +
  aes(x = "", y = coverage, fill = continent) +
  geom_boxplot() +
  scale_fill_viridis_d(option = "plasma", direction = 1) +
  theme_minimal() +
  facet_wrap(vars(vaccine), 
             nrow = 1) +
  labs(x = "Regiões",
       y = "Cobertura",
       titulo = "Cobertura vacinal por região, em 2000") +
  scale_fill_lancet()  
## Scale for fill is already present.
## Adding another scale for fill, which will replace the existing scale.
## Warning: Removed 216 rows containing non-finite outside the scale range
## (`stat_boxplot()`).

Múltiplos gráficos

# Múltiplos gráficos ----
#Todas as linhas
data_long_standardized %>%
 filter(year >= 2012& year <= 2022) %>%
 filter(region %in% "LACR") %>%
 ggplot() +
  aes(x = year, y = coverage, color = name) +
  geom_line() +
  theme_minimal() + 
  facet_wrap(vars(vaccine), scales = "free_x") 

#Fica muito poluído

Isolando linhas com filter()

#Highlight linhas específicas

#Método 1
br_cov = data_long_standardized %>%
 filter(year >= 2012 & year <= 2022,
        name %in% c("Brazil", "Colombia")) %>%
 ggplot() +
  aes(x = year, 
      y = coverage,
      colour = name) +
  
  geom_line(linewidth = 2) +

  theme_minimal() +
  
  facet_wrap(vars(vaccine)) + 
  
  labs(title = "Cobertura vacinal, por vacina",
       x = "Ano",
       y = "Cobertura (%)")  +
  
  scale_color_npg() 

br_cov 

Isolando linhas com gghighlight()

#Método 2
br_cov = data_long_standardized %>%
 filter(year >= 2012 & year <= 2022,
        region %in% c("LACR")) %>%
 ggplot() +
  
  geom_line(aes(x = year, 
      y = coverage,
      colour = name),
      linewidth = 2) +

  theme_minimal() +
  
  theme(axis.text.x = element_text(angle = 90)) +
  
  facet_wrap(vars(vaccine)) + 
  
  labs(title = "Cobertura vacinal, por vacina",
       x = "Ano",
       y = "Cobertura (%)") +
  
  gghighlight(name %in% c("Brazil", "Colombia"), 
              calculate_per_facet = T, #Add quando tiver facets
              unhighlighted_params = list(linewidth = 1, 
                                          colour = "gray90", 
                                          alpha = 0.3)) +
  scale_color_npg() 
## Warning: Tried to calculate with group_by(), but the calculation failed.
## Falling back to ungrouped filter operation...
## label_key: name
br_cov
## Warning: Removed 175 rows containing missing values or values outside the scale range
## (`geom_line()`).

#Mortes
br_mortes = data_long_annotated %>%
 filter(year >= 2012 & year <= 2022,
        region %in% c("LACR")) %>% 
  select(name, year, total_deaths, death_rate_100thousand, disease_vac) %>% 
  distinct() %>%
  drop_na(total_deaths) %>% 
 ggplot() +
  geom_line(aes(x = round(year, 0), 
      y = total_deaths,
      colour = name),
      linewidth = 2) +

  theme_minimal() +
  
  facet_wrap(vars(disease_vac), 
             scales = "free", 
             nrow = 3) + 
  
  labs(title = "Mortes por doença imunoprevenível",
       x = "Ano",
       y = "Mortes") +
  
  #highlight
  gghighlight(name %in% c("Brazil", "Colombia"), #Linhas somente com name == "Brazil'
              
              calculate_per_facet = T, #Add quando tiver facets
              
              unhighlighted_params = list(linewidth = 1, #Opções para linhas não marcadas
                                          colour = "gray90", 
                                          alpha = 0.5)) + 
  scale_color_npg() 
## Warning: Tried to calculate with group_by(), but the calculation failed.
## Falling back to ungrouped filter operation...
## label_key: name
br_mortes 

# Unir gráficos
ggsave(br_cov + br_mortes, file = "br_cov_mortes.png") 
## Saving 7 x 5 in image
## Warning: Removed 175 rows containing missing values or values outside the scale range
## (`geom_line()`).

6. Modelo

Este modelo é útil para você criar gráficos de forma mais fácil, considerando as layers, funções e argumentos mais utilizados no ggplot. Caso queira gerar outros tipos de gráficos, use diferentes geometrias e consulte o (R graph gallery)[https://r-graph-gallery.com/].

Analisando a distribuição

Quantos países por continente registraram os dados na UNICEF?

#Quantos países por continente registraram os dados na UNICEF?

#Todos os continentes juntos
data_long_annotated %>%
 filter(type == "country",
        continent != "Other") %>% 
 select(coverage, year, continent, vaccine) %>% 
 drop_na(coverage) %>% 
 ggplot() +
  aes(x = year, fill = continent) +
  geom_histogram(bins = 43L) +
  theme_minimal() +
  facet_wrap(vars(vaccine)) +
  scale_fill_npg()

Continentes separados

# Continentes separados
data_long_annotated %>%
 filter(type == "country",
        continent != "Other") %>% 
 select(coverage, year, continent, vaccine) %>% 
 drop_na(coverage) %>% 
 ggplot() +
  aes(x = year, fill = continent) +
  geom_histogram(bins = 43L) +
  scale_fill_hue(direction = 1) +
  theme_minimal() +
  facet_grid(continent ~ vaccine, scales = "free")

Quantos países aumentaram sua cobertura vacinal em cada decada?

#Quantos países aumentaram sua cobertura vacinal em cada decada?

data_long_annotated %>%
 filter(type == "country",
        continent != "Other",
        year %in% c(1990, 2000, 2010, 2019)) %>%
 ggplot() +
  aes(x = coverage, fill = continent) +
  geom_histogram(bins = 10L) +
  theme_minimal() +
  theme(plot.caption = element_text(size = 13L),
        legend.position = "top",
        strip.text.y = element_text(angle = 0, 
                                    hjust = 0)) +
  facet_grid(~disease_vac~year, scales = "free") +
  facet_grid(continent ~ vaccine, scales = "free")
## Warning: Removed 1913 rows containing non-finite outside the scale range
## (`stat_bin()`).

Avançado: Dados demográficos e economicos com o Gapminder

O gapminder é um site e um pacote que apresenta diferentes dados sobre países ao longo dos anos. O pacote do R traz uma tabela dos anos 50 até 2007, com dados sobre expectativa de vida, PIB percapita e tamanho da população.

install.packages("gapminder")
## Installing package into 'C:/Users/Wasim/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'gapminder' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\Wasim\AppData\Local\Temp\RtmpuAbSkE\downloaded_packages
library(gapminder)
## Warning: package 'gapminder' was built under R version 4.3.3
gapminder %>% 
  filter(year %in% c(1952, 1982, 2002)) %>% 
ggplot() +
  aes(
    x = gdpPercap,
    y = lifeExp,
    colour = continent,
    size = pop,
    group = country
  ) +
  geom_point(shape = "circle") +
  scale_x_continuous(trans = "log10") +
  theme_minimal() +
  facet_wrap(vars(year), scales = "free_x") +
  gghighlight(country == "China") +
  scale_color_npg()
## Warning: Tried to calculate with group_by(), but the calculation failed.
## Falling back to ungrouped filter operation...
## label_key: country