The data frame you define does not give the values of lvl that you show. In the code below, I demonstrate that and I take a guess at what you did mean to do. Does that help?
v1 <- c('D7','X',23)
v2 <- c('D7','Y',56)
v3 <- c('D7','Z',84)
v4 <- c('D8','X',11)
v5 <- c('D8','Y',12)
v6 <- c('D8','Z',35)
book <- data.frame(v1,v2,v3,v4,v5,v6)
lvl <- unique(book[,1])
#The values of lvl do not match what you show
lvl
#> [1] "D7" "X" "23"
#Is this what you intended to have as the initial data?
book2 <- as.data.frame(t(book))
book2
#> V1 V2 V3
#> v1 D7 X 23
#> v2 D7 Y 56
#> v3 D7 Z 84
#> v4 D8 X 11
#> v5 D8 Y 12
#> v6 D8 Z 35
#Does this give you the result you want?
library(tidyr)
book2_wide <- pivot_wider(book2, names_from = V2, values_from = V3)
book2_wide
#> # A tibble: 2 × 4
#> V1 X Y Z
#> <chr> <chr> <chr> <chr>
#> 1 D7 23 56 84
#> 2 D8 11 12 35
Thank you!
I obtained the levels from a list that extracted only the first column, but it really does not matter, I think your method works, great thanks!