1) pivot_longer Измените кадр данных дважды так:
library(dplyr)
library(tidyr)
DF %>%
pivot_longer(starts_with("Type"), values_to = "Type") %>%
select(-name) %>%
pivot_longer(c("HP", "ATK", "DEF"), names_to = "Stat", values_to = "Value")
, получив:
# A tibble: 6 x 5
ID Name Type Stat Value
<chr> <chr> <chr> <chr> <int>
1 001 Bulba.. Grass HP 45
2 001 Bulba.. Grass ATK 49
3 001 Bulba.. Grass DEF 49
4 001 Bulba.. Poison HP 45
5 001 Bulba.. Poison ATK 49
6 001 Bulba.. Poison DEF 49
2) плавить поочередноиспользуйте melt
из data.table дважды.
library(data.table)
m1 <- melt(DF, measure.var = grep("Type", names(DF)), value.name = "Type")
melt(m1, measure.var = c("HP", "ATK", "DEF"),
variable.name = "Stat", value.name = "Value")[-3]
, давая:
ID Name Type Stat Value
1 001 Bulba.. Grass HP 45
2 001 Bulba.. Poison HP 45
3 001 Bulba.. Grass ATK 49
4 001 Bulba.. Poison ATK 49
5 001 Bulba.. Grass DEF 49
6 001 Bulba.. Poison DEF 49
Примечание
DF
в воспроизводимой форме предполагалось равным:
Lines <- "
ID Name Type1 Type2 HP ATK DEF
001 Bulba.. Grass Poison 45 49 49"
DF <- read.table(text = Lines, header = TRUE, as.is = TRUE,
colClasses = list(ID = "character"))