The cdata
package (where a lot of the newer pivot methods are from) has some neat notation both for specifying and describing transforms like this. In the interest of breadth of solutions, you might want to consider including some of these. Nina Zumel, and I, worked really hard to develop the methodology and teaching materials.
juniors_multiple <- tibble::tribble(
~ "baker", ~"score_1", ~"score_2", ~"score_3", ~ "guess_1", ~"guess_2", ~"guess_3",
"Emma", 1L, 0L, 1L, "cinnamon", "cloves", "nutmeg",
"Harry", 1L, 1L, 1L, "cinnamon", "cardamom", "nutmeg",
"Ruby", 1L, 0L, 1L, "cinnamon", "cumin", "nutmeg",
"Zainab", 0L, NA, 0L, "cardamom", NA_character_, "cinnamon"
)
library("cdata")
control_table <- wrapr::qchar_frame(
"order" , "score" , "guess" |
"1" , score_1 , guess_1 |
"2" , score_2 , guess_2 |
"3" , score_3 , guess_3 )
rowrecs_to_blocks(juniors_multiple, control_table, columnsToCopy = "baker")
#> baker order score guess
#> 1 Emma 1 1 cinnamon
#> 2 Emma 2 0 cloves
#> 3 Emma 3 1 nutmeg
#> 4 Harry 1 1 cinnamon
#> 5 Harry 2 1 cardamom
#> 6 Harry 3 1 nutmeg
#> 7 Ruby 1 1 cinnamon
#> 8 Ruby 2 0 cumin
#> 9 Ruby 3 1 nutmeg
#> 10 Zainab 1 0 cardamom
#> 11 Zainab 2 NA <NA>
#> 12 Zainab 3 0 cinnamon
juniors_multiple <- tibble::tribble(
~ "baker", ~"score_1", ~"score_2", ~"score_3", ~ "guess_1", ~"guess_2", ~"guess_3",
"Emma", 1L, 0L, 1L, "cinnamon", "cloves", "nutmeg",
"Harry", 1L, 1L, 1L, "cinnamon", "cardamom", "nutmeg",
"Ruby", 1L, 0L, 1L, "cinnamon", "cumin", "nutmeg",
"Zainab", 0L, NA, 0L, "cardamom", NA_character_, "cinnamon"
)
library("cdata")
control_table <- wrapr::qchar_frame(
"order" , "score" , "guess" |
"1" , score_1 , guess_1 |
"2" , score_2 , guess_2 |
"3" , score_3 , guess_3 )
transform <- cdata::rowrecs_to_blocks_spec(
control_table,
recordKeys = "baker")
juniors_multiple %.>% transform
#> baker order score guess
#> 1 Emma 1 1 cinnamon
#> 2 Emma 2 0 cloves
#> 3 Emma 3 1 nutmeg
#> 4 Harry 1 1 cinnamon
#> 5 Harry 2 1 cardamom
#> 6 Harry 3 1 nutmeg
#> 7 Ruby 1 1 cinnamon
#> 8 Ruby 2 0 cumin
#> 9 Ruby 3 1 nutmeg
#> 10 Zainab 1 0 cardamom
#> 11 Zainab 2 NA <NA>
#> 12 Zainab 3 0 cinnamon
print(transform)
#> {
#> row_record <- wrapr::qchar_frame(
#> "baker" , "score_1", "score_2", "score_3", "guess_1", "guess_2", "guess_3" |
#> . , score_1 , score_2 , score_3 , guess_1 , guess_2 , guess_3 )
#> row_keys <- c('baker')
#>
#> # becomes
#>
#> block_record <- wrapr::qchar_frame(
#> "baker" , "order", "score", "guess" |
#> . , "1" , score_1, guess_1 |
#> . , "2" , score_2, guess_2 |
#> . , "3" , score_3, guess_3 )
#> block_keys <- c('baker', 'order')
#>
#> # args: c(checkNames = TRUE, checkKeys = TRUE, strict = FALSE)
#> }