Galera bom dia!
Item |
Tipo |
Metrica |
Rank |
A |
Altura |
600 |
1 |
A |
Largura |
400 |
3 |
A |
Comprimento |
550 |
2 |
B |
Altura |
600 |
1 |
B |
Largura |
600 |
2 |
B |
Comprimento |
550 |
3 |
Na tabela acima gostaria de gerar um calculo Rank por grupo coluna Item.
Sabem com Fazer isso no R?
Desde já agradeço atenção.
clente
2
Joel,
Não sei se entendi a pergunta, mas abaixo trago duas soluções:
library(magrittr)
# Tabela exemplo
df <- dplyr::tribble(
~item, ~tipo, ~metrica,
"A", "Altura", "600",
"A", "Largura", "400",
"A", "Comprimento", "550",
"B", "Altura", "600",
"B", "Largura", "600",
"B", "Comprimento", "550"
)
# Se você quiser manter os empates
df %>%
dplyr::group_by(item) %>%
dplyr::mutate(rank = dplyr::dense_rank(dplyr::desc(metrica)))
#> # A tibble: 6 x 4
#> # Groups: item [2]
#> item tipo metrica rank
#> <chr> <chr> <chr> <int>
#> 1 A Altura 600 1
#> 2 A Largura 400 3
#> 3 A Comprimento 550 2
#> 4 B Altura 600 1
#> 5 B Largura 600 1
#> 6 B Comprimento 550 2
# Se você quiser desempatar (embaralha a tabela)
df %>%
dplyr::group_by(item) %>%
dplyr::arrange(dplyr::desc(metrica), tipo) %>%
dplyr::mutate(rank = dplyr::row_number())
#> # A tibble: 6 x 4
#> # Groups: item [2]
#> item tipo metrica rank
#> <chr> <chr> <chr> <int>
#> 1 A Altura 600 1
#> 2 B Altura 600 1
#> 3 B Largura 600 2
#> 4 A Comprimento 550 2
#> 5 B Comprimento 550 3
#> 6 A Largura 400 3
Created on 2020-12-21 by the reprex package (v0.3.0)
1 curtida
Top! Era isso mesmo.
dplyr… tem poderes fenomenais!
Muito obrigado!
1 curtida