Como reordenar linhas de uma coluna

Olá a todos.

  1. O data frame estimativa_por_idade possui a distribuição de uma população por idade;

IDADE | 2014 | 2015 | …| 2016| Local
0 | 1401 | 1437 | … | 1427 | Itacoatiara
1 | 1380 | 1406 | … | 1434 | Itacoatiara

+90 | 267 | 288 | … | 373 | Itacoatiara

  1. O código a seguir, cria uma nova coluna de faixa-etária:

estimativas_por_idade <- estimativas_por_idade %>%
mutate(
Faixa_Etaria = case_when(
IDADE %in% 0:3 ~ “0 a 3 anos”,
IDADE %in% 4:5 ~ “4 a 5 anos”,
IDADE %in% 6:14 ~ “6 a 14 anos”,
IDADE %in% 15:17 ~ “15 a 17 anos”,
IDADE >17 ~ “mais de 18 anos”))

  1. O código a seguir, agrupa os dados, por faixa-etária

tabela <- estimativas_por_idade %>%
filter(Local == “Itacoatiara”) %>%
group_by(Faixa_Etaria) %>%
summarise(
“Pop 2014” = sum(2014),
“Pop 2015” = sum(2015),
“Pop 2016” = sum(2016),
“Pop 2017” = sum(2017),
“Pop 2018” = sum(2018),
“Pop 2019” = sum(2019),
“Pop 2020” = sum(2020),
)

RESULTADO:

FAIXA-ETÁRIA | POP 2014 | … | POP 2020
0 a 3 anos | 5514 | … | 5517
15 a 17 anos | 4977 | … | 4517
4 a 5 anos | 2882 | … | 2882
6 a 14 anos | 13392 | … | 12831
mais de 18 anos | 69040 | … | 76750

Dúvida: Como faço para reordenar a coluna FAIXA-ETÁRIA na ordem correta?

Olá, Hidelbrando.

Tive que criar um dataset aleatório no excel tentando replicar a sua base, espero que seja um bom exemplo.

Acredito que tem várias formas de fazer isso, porém utilizei a que considero mais prática, por funcionar dentro de gráficos também. Que é basicamente definir a ordem que você quer dentro de um factor, assim ele vai seguir a ordem interna sempre que necessário.

Segue minha solução:

# carrega pacotes
library(dplyr)
#> Warning: package 'dplyr' was built under R version 4.0.3
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

estimativas_por_idade <- 
  tibble::tribble(
  ~IDADE, ~`2014`, ~`2015`, ~`2016`, ~`2017`, ~`2018`, ~`2019`, ~`2020`,
      0L,    894L,    949L,    491L,    334L,    629L,    559L,    830L,
      1L,    569L,    340L,    222L,    476L,    555L,    111L,    910L,
      2L,    299L,     72L,    587L,     82L,    136L,    784L,    958L,
      3L,    203L,     36L,    958L,     85L,    681L,    394L,    833L,
      4L,    705L,    333L,    331L,    517L,    944L,    841L,    843L,
      5L,    468L,    599L,    336L,    997L,    371L,    430L,    689L,
      6L,    265L,    628L,      1L,    853L,    728L,    171L,    884L,
      7L,    239L,    921L,    182L,    300L,    618L,    266L,    916L,
      8L,    386L,    348L,    751L,     40L,    338L,    244L,    923L,
      9L,    506L,    523L,    326L,    641L,    546L,    669L,    410L,
     10L,    542L,    602L,    593L,    374L,    245L,    146L,    355L,
     11L,    695L,    597L,    161L,    754L,    588L,    461L,     80L,
     12L,    531L,    647L,    878L,    371L,    558L,    646L,      5L,
     13L,     90L,    940L,    241L,    743L,    278L,    793L,    287L,
     14L,    830L,     30L,    385L,    470L,    630L,    256L,    872L,
     15L,    558L,    757L,    424L,    906L,    254L,    545L,    121L,
     16L,    848L,    937L,    594L,    374L,    618L,    795L,    723L,
     17L,    349L,    872L,    763L,    963L,    542L,    276L,    798L,
     18L,    630L,     27L,     95L,    334L,    858L,    745L,    903L,
     19L,    545L,    398L,    693L,    410L,    837L,    240L,    335L,
     20L,    975L,    539L,    754L,    882L,    737L,    179L,    628L,
     21L,    520L,    692L,    546L,    735L,    628L,    518L,    151L,
     22L,    487L,    629L,    556L,    854L,    444L,    948L,    462L,
     23L,    100L,    542L,    847L,    728L,    700L,    471L,    713L,
     24L,    497L,    210L,    749L,   1000L,    962L,    470L,    314L
  )


estimativas_por_idade <-
  estimativas_por_idade %>%
  mutate(
    Faixa_Etaria = case_when(
      IDADE %in% 0:3 ~ "0 a 3 anos",
      IDADE %in% 4:5 ~ "4 a 5 anos",
      IDADE %in% 6:14 ~ "6 a 14 anos",
      IDADE %in% 15:17 ~ "15 a 17 anos",
      IDADE >17 ~ "mais de 18 anos"))


tabela <- estimativas_por_idade %>%
  group_by(Faixa_Etaria) %>%
  summarise(
    "Pop 2014" = sum(2014),
    "Pop 2015" = sum(2015),
    "Pop 2016" = sum(2016),
    "Pop 2017" = sum(2017),
    "Pop 2018" = sum(2018),
    "Pop 2019" = sum(2019),
    "Pop 2020" = sum(2020),
  )

###### mudanças a partir daqui ######

#ordena a coluna faixa etaria por fator e define que a ordem é TRUE
tabela <-
  tabela %>%
  mutate(Faixa_Etaria = factor(
    Faixa_Etaria,
    levels = c("0 a 3 anos",
               "4 a 5 anos",
               "6 a 14 anos",
               "15 a 17 anos",
               "mais de 18 anos"),
    ordered = TRUE
  ))

# classifica a tabela de acordo com a própria coluna de faixa etaria (agora ela tem uma ordem definida pelo factor)
tabela %>% 
  arrange(Faixa_Etaria)
#> # A tibble: 5 x 8
#>   Faixa_Etaria `Pop 2014` `Pop 2015` `Pop 2016` `Pop 2017` `Pop 2018` `Pop 2019`
#>   <ord>             <dbl>      <dbl>      <dbl>      <dbl>      <dbl>      <dbl>
#> 1 0 a 3 anos         2014       2015       2016       2017       2018       2019
#> 2 4 a 5 anos         2014       2015       2016       2017       2018       2019
#> 3 6 a 14 anos        2014       2015       2016       2017       2018       2019
#> 4 15 a 17 anos       2014       2015       2016       2017       2018       2019
#> 5 mais de 18 ~       2014       2015       2016       2017       2018       2019
#> # ... with 1 more variable: Pop 2020 <dbl>

Created on 2021-04-05 by the reprex package (v1.0.0)

Segue capítulo do livro da Curso R sobre fatores:

Ah, por último, quando fizer perguntas, por gentileza, tenta colocar um dataset mínimo para servir de exemplo reprodutível (tem um vídeo da Bea em que ela ensina a usar o pacote datapasta, da pra criar uma base no excel e depois colar no script, gerando um dataframe ou tibble).

Assim facilita a vida de quem for tentar responder e eventualmente até aumenta a velocidade com que você pode receber sua resposta.

Espero que tenha ajudado.

Abraços.

Boa noite Maykon

Deu certo. Muito obrigado!!!

Ah! E obrigado pela dica de como melhorar a pergunta. Achei que se colocasse a base ia ficar pior, mas é exatamente o contrario.

Gratidão!!!

1 curtida

Olá, pessoal! Tudo bom? Só para ficar registrado para futuras consultas, o correto seria:

(tabela <- estimativas_por_idade %>%
  group_by(Faixa_Etaria) %>%
  summarise(
    "Pop 2014" = sum(`2014`),
    "Pop 2015" = sum(`2015`),
    "Pop 2016" = sum(`2016`),
    "Pop 2017" = sum(`2017`),
    "Pop 2018" = sum(`2018`),
    "Pop 2019" = sum(`2019`),
    "Pop 2020" = sum(`2020`),
  ))
#> # A tibble: 5 x 8
#>   Faixa_Etaria `Pop 2014` `Pop 2015` `Pop 2016` `Pop 2017` `Pop 2018` `Pop 2019`
#>   <chr>             <int>      <int>      <int>      <int>      <int>      <int>
#> 1 0 a 3 anos         1965       1397       2258        977       2001       1848
#> 2 15 a 17 anos       1755       2566       1781       2243       1414       1616
#> 3 4 a 5 anos         1173        932        667       1514       1315       1271
#> 4 6 a 14 anos        4084       5236       3518       4546       4529       3652
#> 5 mais de 18 ~       3754       3037       4240       4943       5166       3571
#> # ... with 1 more variable: Pop 2020 <int>

Created on 2021-04-06 by the reprex package (v2.0.0)

Como sugestão, uma maneira fancy de fazer isso e mais enxuta seria:

(tabela <- estimativas_por_idade %>%
group_by(Faixa_Etaria) %>%
summarise(across(.cols = -1, .fns = sum, .names = "POP_{.col}")))
#> # A tibble: 5 x 8
#>   Faixa_Etaria    POP_2014 POP_2015 POP_2016 POP_2017 POP_2018 POP_2019 POP_2020
#>   <chr>              <int>    <int>    <int>    <int>    <int>    <int>    <int>
#> 1 0 a 3 anos          1965     1397     2258      977     2001     1848     3531
#> 2 15 a 17 anos        1755     2566     1781     2243     1414     1616     1642
#> 3 4 a 5 anos          1173      932      667     1514     1315     1271     1532
#> 4 6 a 14 anos         4084     5236     3518     4546     4529     3652     4732
#> 5 mais de 18 anos     3754     3037     4240     4943     5166     3571     3506

Created on 2021-04-06 by the reprex package (v2.0.0)

1 curtida

Ótima colocação, Rafael.
Como foquei na parte de organizar a ordem, nem olhei se o agrupamento estava correto ou não.
Interessante a abordagem pelo across, eu não conhecia. Ele faz o agrupamento para todas as colunas que começam com “POP” ?

Olá. Apareceu o seguinte erro quando fui reproduzir o código acima:

Erro: Problem with `summarise()` input `..1`. x 'type' inválido (character) do argumento i Input `..1` is `(function (.cols = everything(), .fns = NULL, ..., .names = NULL) ...`. i The error occurred in group 1: Faixa_Etaria = "0 a 3 anos". Run `rlang::last_error()` to see where the error occurred..

Você pode me ajudar no que deve está dando de errado no meu, já que aqui está funcionando?

Hidelbrando, você reproduziu o código completo?

Eu executei aqui e não gerou erro. Segue reprex:

library(magrittr)

base_estimativas_por_idade <- 
  tibble::tribble(
    ~IDADE, ~`2014`, ~`2015`, ~`2016`, ~`2017`, ~`2018`, ~`2019`, ~`2020`,
    0L,    894L,    949L,    491L,    334L,    629L,    559L,    830L,
    1L,    569L,    340L,    222L,    476L,    555L,    111L,    910L,
    2L,    299L,     72L,    587L,     82L,    136L,    784L,    958L,
    3L,    203L,     36L,    958L,     85L,    681L,    394L,    833L,
    4L,    705L,    333L,    331L,    517L,    944L,    841L,    843L,
    5L,    468L,    599L,    336L,    997L,    371L,    430L,    689L,
    6L,    265L,    628L,      1L,    853L,    728L,    171L,    884L,
    7L,    239L,    921L,    182L,    300L,    618L,    266L,    916L,
    8L,    386L,    348L,    751L,     40L,    338L,    244L,    923L,
    9L,    506L,    523L,    326L,    641L,    546L,    669L,    410L,
    10L,    542L,    602L,    593L,    374L,    245L,    146L,    355L,
    11L,    695L,    597L,    161L,    754L,    588L,    461L,     80L,
    12L,    531L,    647L,    878L,    371L,    558L,    646L,      5L,
    13L,     90L,    940L,    241L,    743L,    278L,    793L,    287L,
    14L,    830L,     30L,    385L,    470L,    630L,    256L,    872L,
    15L,    558L,    757L,    424L,    906L,    254L,    545L,    121L,
    16L,    848L,    937L,    594L,    374L,    618L,    795L,    723L,
    17L,    349L,    872L,    763L,    963L,    542L,    276L,    798L,
    18L,    630L,     27L,     95L,    334L,    858L,    745L,    903L,
    19L,    545L,    398L,    693L,    410L,    837L,    240L,    335L,
    20L,    975L,    539L,    754L,    882L,    737L,    179L,    628L,
    21L,    520L,    692L,    546L,    735L,    628L,    518L,    151L,
    22L,    487L,    629L,    556L,    854L,    444L,    948L,    462L,
    23L,    100L,    542L,    847L,    728L,    700L,    471L,    713L,
    24L,    497L,    210L,    749L,   1000L,    962L,    470L,    314L
  )


estimativas_por_idade <-
  base_estimativas_por_idade %>%
  dplyr::mutate(
    Faixa_Etaria = dplyr::case_when(
      IDADE %in% 0:3 ~ "0 a 3 anos",
      IDADE %in% 4:5 ~ "4 a 5 anos",
      IDADE %in% 6:14 ~ "6 a 14 anos",
      IDADE %in% 15:17 ~ "15 a 17 anos",
      IDADE >17 ~ "mais de 18 anos"))


tabela <- estimativas_por_idade %>%
    dplyr::group_by(Faixa_Etaria) %>%
    dplyr::summarise(dplyr::across(.cols = -1, .fns = sum, .names = "POP_{.col}"))

tabela
#> # A tibble: 5 x 8
#>   Faixa_Etaria    POP_2014 POP_2015 POP_2016 POP_2017 POP_2018 POP_2019 POP_2020
#>   <chr>              <int>    <int>    <int>    <int>    <int>    <int>    <int>
#> 1 0 a 3 anos          1965     1397     2258      977     2001     1848     3531
#> 2 15 a 17 anos        1755     2566     1781     2243     1414     1616     1642
#> 3 4 a 5 anos          1173      932      667     1514     1315     1271     1532
#> 4 6 a 14 anos         4084     5236     3518     4546     4529     3652     4732
#> 5 mais de 18 anos     3754     3037     4240     4943     5166     3571     3506

Created on 2021-05-06 by the reprex package (v2.0.0)

Tenta executar esse código acima (que é uma composição dos códigos postados), e caso gere erro, envie aqui o exemplo reprodutível que apresente o erro (com reprex, selecionando o código e clicando no addin “Reprex Selection”.

Abraços!

1 curtida

Obrigado Bea.

Acho que estava misturando os dois códigos. Agora deu certo.

Gratidão.

1 curtida