library(tidyverse)
## define the example tibble
dat <-
tribble(
~individual, ~Q1_A, ~Q1_B, ~Q1_C, ~Q1_D, ~Q2_A, ~Q2_B, ~Q2_C, ~Q2_D,
"alice", NA, "cat", NA, NA, "tacos", NA, NA, NA,
"bob", "dog", NA, NA, NA, NA, NA, NA, "pizza"
)
## first ... use pivot_longer to get all of the "question columns" (starting with Q)
## this will split the question columns into two columns (question and choice) by the "_"
## the values will be the answer
## the values_drop_na=TRUE will exclude the responses that have NA (i.e., the "non choices")
dat %>%
pivot_longer(cols = starts_with("Q"), names_prefix = "", names_sep = "_", names_to = c("question","choice"), values_to = c("answer"), values_drop_na = TRUE)
#> # A tibble: 4 × 4
#> individual question choice answer
#> <chr> <chr> <chr> <chr>
#> 1 alice Q1 B cat
#> 2 alice Q2 A tacos
#> 3 bob Q1 A dog
#> 4 bob Q2 D pizza
Created on 2024-08-12 with reprex v2.0.2