Exercício 2 - Manipulação de Dados

Author

Luana

Aula 2 - Manipulação de Dados

Vamos usar um conjunto de dados do tidytuesday

E os dados escolhidos por mim foram o de produção de ovos nos EUA

Então a primira coisa que vocês terão que fazer é ler sobre os dados no link acima, baixar os dados de acordo com as instruções, carregar o tidyverse e seguir as orientações abaixo!

Só vamos usar UM conjunto de dados
#install.packages("readr") 
library(readr)
#install.packages("tidyverse") 
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.2     ✔ purrr     1.0.1
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.2     ✔ tibble    3.2.1
✔ lubridate 1.9.2     ✔ tidyr     1.3.0
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
eggprod<-readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2023/2023-04-11/egg-production.csv')
Rows: 220 Columns: 6
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr  (3): prod_type, prod_process, source
dbl  (2): n_hens, n_eggs
date (1): observed_month

ℹ 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.
str(eggprod)
spc_tbl_ [220 × 6] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
 $ observed_month: Date[1:220], format: "2016-07-31" "2016-08-31" ...
 $ prod_type     : chr [1:220] "hatching eggs" "hatching eggs" "hatching eggs" "hatching eggs" ...
 $ prod_process  : chr [1:220] "all" "all" "all" "all" ...
 $ n_hens        : num [1:220] 57975000 57595000 57161000 56857000 57116000 ...
 $ n_eggs        : num [1:220] 1.15e+09 1.14e+09 1.09e+09 1.13e+09 1.10e+09 ...
 $ source        : chr [1:220] "ChicEggs-09-23-2016.pdf" "ChicEggs-10-21-2016.pdf" "ChicEggs-11-22-2016.pdf" "ChicEggs-12-23-2016.pdf" ...
 - attr(*, "spec")=
  .. cols(
  ..   observed_month = col_date(format = ""),
  ..   prod_type = col_character(),
  ..   prod_process = col_character(),
  ..   n_hens = col_double(),
  ..   n_eggs = col_double(),
  ..   source = col_character()
  .. )
 - attr(*, "problems")=<externalptr> 
head(eggprod)
# A tibble: 6 × 6
  observed_month prod_type     prod_process   n_hens     n_eggs source          
  <date>         <chr>         <chr>           <dbl>      <dbl> <chr>           
1 2016-07-31     hatching eggs all          57975000 1147000000 ChicEggs-09-23-…
2 2016-08-31     hatching eggs all          57595000 1142700000 ChicEggs-10-21-…
3 2016-09-30     hatching eggs all          57161000 1093300000 ChicEggs-11-22-…
4 2016-10-31     hatching eggs all          56857000 1126700000 ChicEggs-12-23-…
5 2016-11-30     hatching eggs all          57116000 1096600000 ChicEggs-01-24-…
6 2016-12-31     hatching eggs all          57750000 1132900000 ChicEggs-02-28-…

Exercício 1

Remover a última coluna dataset (a coluna chamada source)

#filt2<-eggprod[,-6]
filt <- select(eggprod, -source)
head(filt)
# A tibble: 6 × 5
  observed_month prod_type     prod_process   n_hens     n_eggs
  <date>         <chr>         <chr>           <dbl>      <dbl>
1 2016-07-31     hatching eggs all          57975000 1147000000
2 2016-08-31     hatching eggs all          57595000 1142700000
3 2016-09-30     hatching eggs all          57161000 1093300000
4 2016-10-31     hatching eggs all          56857000 1126700000
5 2016-11-30     hatching eggs all          57116000 1096600000
6 2016-12-31     hatching eggs all          57750000 1132900000

Exercício 2

Selecionar apenas as variáveis numéricas

num<-select_if(eggprod, is.numeric)

head(num)
# A tibble: 6 × 2
    n_hens     n_eggs
     <dbl>      <dbl>
1 57975000 1147000000
2 57595000 1142700000
3 57161000 1093300000
4 56857000 1126700000
5 57116000 1096600000
6 57750000 1132900000

Exercício 3

Criar um dataset só com hatching e outro dataset apenas com table eggs

hatch<-subset(filt, prod_type == "hatching eggs")
head(hatch)
# A tibble: 6 × 5
  observed_month prod_type     prod_process   n_hens     n_eggs
  <date>         <chr>         <chr>           <dbl>      <dbl>
1 2016-07-31     hatching eggs all          57975000 1147000000
2 2016-08-31     hatching eggs all          57595000 1142700000
3 2016-09-30     hatching eggs all          57161000 1093300000
4 2016-10-31     hatching eggs all          56857000 1126700000
5 2016-11-30     hatching eggs all          57116000 1096600000
6 2016-12-31     hatching eggs all          57750000 1132900000
table<-subset(filt, prod_type == "table eggs")
head(hatch)
# A tibble: 6 × 5
  observed_month prod_type     prod_process   n_hens     n_eggs
  <date>         <chr>         <chr>           <dbl>      <dbl>
1 2016-07-31     hatching eggs all          57975000 1147000000
2 2016-08-31     hatching eggs all          57595000 1142700000
3 2016-09-30     hatching eggs all          57161000 1093300000
4 2016-10-31     hatching eggs all          56857000 1126700000
5 2016-11-30     hatching eggs all          57116000 1096600000
6 2016-12-31     hatching eggs all          57750000 1132900000

Exercício 4

Criar um dataset só com table eggs e todos os processos (all)

tableall<-subset(filt, prod_type == "table eggs" & prod_process == "all")
head(tableall)
# A tibble: 6 × 5
  observed_month prod_type  prod_process    n_hens     n_eggs
  <date>         <chr>      <chr>            <dbl>      <dbl>
1 2016-07-31     table eggs all          299669000 7350500000
2 2016-08-31     table eggs all          300917000 7409000000
3 2016-09-30     table eggs all          303270000 7204200000
4 2016-10-31     table eggs all          305852000 7534700000
5 2016-11-30     table eggs all          310728000 7468500000
6 2016-12-31     table eggs all          318820000 7950400000

Exercício 5

Mudar os nomes das variáveis para português

port<-rename(filt, 'mês observado'=observed_month, 'tipo_do_produto'=prod_type ,processo = prod_process,  'n de galinhas'=n_hens, 'n de ovos'=n_eggs)

head(port)
# A tibble: 6 × 5
  `mês observado` tipo_do_produto processo `n de galinhas` `n de ovos`
  <date>          <chr>           <chr>              <dbl>       <dbl>
1 2016-07-31      hatching eggs   all             57975000  1147000000
2 2016-08-31      hatching eggs   all             57595000  1142700000
3 2016-09-30      hatching eggs   all             57161000  1093300000
4 2016-10-31      hatching eggs   all             56857000  1126700000
5 2016-11-30      hatching eggs   all             57116000  1096600000
6 2016-12-31      hatching eggs   all             57750000  1132900000

Exercício 6

Mudar os nomes dos fatores para português

portfat<-mutate(port, tipo_do_produto=recode(tipo_do_produto, `hatching eggs`="ovos de incubação" , `table eggs`="ovos de mesa"), processo =recode(processo, `cage-free (non-organic)`= "gaiolas livre (n orgânicos)", all="todos", `cage-free (organic)`="gaiolas livre (orgânicos)"))

head(portfat)
# A tibble: 6 × 5
  `mês observado` tipo_do_produto   processo `n de galinhas` `n de ovos`
  <date>          <chr>             <chr>              <dbl>       <dbl>
1 2016-07-31      ovos de incubação todos           57975000  1147000000
2 2016-08-31      ovos de incubação todos           57595000  1142700000
3 2016-09-30      ovos de incubação todos           57161000  1093300000
4 2016-10-31      ovos de incubação todos           56857000  1126700000
5 2016-11-30      ovos de incubação todos           57116000  1096600000
6 2016-12-31      ovos de incubação todos           57750000  1132900000

Exercício 7

Criar uma nova variável chamada ‘produtividade’ com a razão entre número de ovos (n_eggs) e número de galinhas (hen)

new<-mutate(portfat, produtividade = (`n de ovos`/ `n de galinhas`))
head(new)
# A tibble: 6 × 6
  `mês observado` tipo_do_produto   processo `n de galinhas` `n de ovos`
  <date>          <chr>             <chr>              <dbl>       <dbl>
1 2016-07-31      ovos de incubação todos           57975000  1147000000
2 2016-08-31      ovos de incubação todos           57595000  1142700000
3 2016-09-30      ovos de incubação todos           57161000  1093300000
4 2016-10-31      ovos de incubação todos           56857000  1126700000
5 2016-11-30      ovos de incubação todos           57116000  1096600000
6 2016-12-31      ovos de incubação todos           57750000  1132900000
# ℹ 1 more variable: produtividade <dbl>

Exercício 8

Criar um dataset só de produtos cage free e criar novas variáveis separando n_eggs e n_hens por organicos e não orgânicos

cf<-filter(filt, prod_process != "all") %>% separate(prod_process, into=c("processo", "tipo"), sep = " ") %>% pivot_wider (names_from=prod_type, values_from=c(n_hens, n_eggs))
head(cf)
# A tibble: 6 × 5
  observed_month processo  tipo          `n_hens_table eggs` `n_eggs_table eggs`
  <date>         <chr>     <chr>                       <dbl>               <dbl>
1 2016-08-31     cage-free (non-organic)            17000000          397884291.
2 2016-09-30     cage-free (non-organic)            17000000          383774914.
3 2016-10-31     cage-free (non-organic)            23500000          546374469.
4 2016-11-30     cage-free (non-organic)            23500000          530864743.
5 2016-12-31     cage-free (non-organic)            23500000          542733120 
6 2017-01-31     cage-free (non-organic)            23500000          550017411.

Exercício 9

Juntar as variáveis n_eggs e n_hens em uma única coluna

junto<- unite(filt,numero, c(n_hens, n_eggs), sep = " ")
head(junto)
# A tibble: 6 × 4
  observed_month prod_type     prod_process numero             
  <date>         <chr>         <chr>        <chr>              
1 2016-07-31     hatching eggs all          57975000 1.147e+09 
2 2016-08-31     hatching eggs all          57595000 1142700000
3 2016-09-30     hatching eggs all          57161000 1093300000
4 2016-10-31     hatching eggs all          56857000 1126700000
5 2016-11-30     hatching eggs all          57116000 1096600000
6 2016-12-31     hatching eggs all          57750000 1132900000

Exercício 10

Faça um sumário dos dados com as médias de n_hens e n_eggs por ano, por produto e por processo

sumar <- separate(filt, observed_month, into = c("year", "month", "day"), sep = "-") %>% 
group_by(year, prod_type, prod_process) %>% 
summarise(med_ovos = mean(n_eggs), med_galinhas = mean(n_hens))
`summarise()` has grouped output by 'year', 'prod_type'. You can override using
the `.groups` argument.
head(sumar)
# A tibble: 6 × 5
# Groups:   year, prod_type [4]
  year  prod_type     prod_process               med_ovos med_galinhas
  <chr> <chr>         <chr>                         <dbl>        <dbl>
1 2016  hatching eggs all                     1123200000     57409000 
2 2016  table eggs    all                     7486216667.   306542667.
3 2016  table eggs    cage-free (non-organic)  480326307.    20900000 
4 2016  table eggs    cage-free (organic)      318542883.    13860000 
5 2017  hatching eggs all                     1123725000     59521833.
6 2017  table eggs    all                     7637800000    314964500 

Fiquei chocada com a quantidade de galinhas e ovos por ano!

galporhab<-57409000/325000000
galporhab
[1] 0.1766431
ovoporhab<- 1123200000/325000000
ovoporhab
[1] 3.456

Quantos ovos uma galinha tem que botar por ano pra produzirem juntas, mais de 1 bilhão de ovos (3x maior que a população dos EUA em 2017)?