library(tidyr)
#> Warning: package 'tidyr' was built under R version 4.0.4
library(dplyr)
#> Warning: package 'dplyr' was built under R version 4.0.4
#>
#> 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
library(tibble)
#> Warning: package 'tibble' was built under R version 4.0.4
library(magrittr)
#> Warning: package 'magrittr' was built under R version 4.0.4
#>
#> Attaching package: 'magrittr'
#> The following object is masked from 'package:tidyr':
#>
#> extract
library(reprex)
#> Warning: package 'reprex' was built under R version 4.0.4
library(styler)
#> Warning: package 'styler' was built under R version 4.0.4
# Criando o tibble para o exemplo.
nome <- c("Tania", "Mara", "Chico", "Marco")
ai_esfera__x <- sample(seq(0, 99, 1), 4, replace = FALSE)
ai_esfera__x3 <- sample(seq(0, 99, 1), 4, replace = FALSE)
ai_esfera__w <- sample(seq(0, 99, 1), 4, replace = FALSE)
ai_cubo__x <- sample(seq(0, 99, 1), 4, replace = FALSE)
ai_cubo__x3 <- sample(seq(0, 99, 1), 4, replace = FALSE)
ai_tetraedro__x3 <- sample(seq(0, 99, 1), 4, replace = FALSE)
dd_esfera__x3 <- sample(seq(0, 99, 1), 4, replace = FALSE)
dd_cubo__x <- sample(seq(0, 99, 1), 4, replace = FALSE)
dd_tetraedro__w <- sample(seq(0, 99, 1), 4, replace = FALSE)
dd_tetraedro__x3 <- sample(seq(0, 99, 1), 4, replace = FALSE)
# Os nomes da colunas indicam respectivamente a origem, tipo e a classe.
# A 4ª coluna tem origem em ai é do tipo esfera e da classe w,
# a última tem origem dd é do tipo tetraedro e classe x3.
exemplo <- tibble(
nome, ai_cubo__x, ai_cubo__x3, ai_esfera__w, ai_esfera__x,
ai_esfera__x3, ai_tetraedro__x3, dd_cubo__x, dd_esfera__x3,
dd_tetraedro__w, dd_tetraedro__x3
)
# Para fazer o exemplo_tidy, usei o pivot_longer 3 vezes.
# Há alguma forma menos repetitiva para obter o mesmo resultado?
# Criando o tibble exemplo_tidy.
exemplo_tidy <- exemplo %>%
pivot_longer(
!nome,
names_to = c(".value", "classe"),
names_sep = "__",
values_drop_na = TRUE
) %>%
pivot_longer(
!nome & !classe,
names_to = c(".value", "tipo"),
names_sep = "_",
values_drop_na = TRUE
) %>%
pivot_longer(!nome & !classe & !tipo,
names_to = "origem", values_to = "valor"
) %>%
select(1, 4, 3, 2, 5)
Created on 2021-03-14 by the reprex package (v1.0.0)