如何重建具有多项选择的分类变量

How to reconstruct a categorical variable with multiple choices

我遇到了以下问题。我正在分析问卷中的数据,向受访者提供了 7 个可能的答案,并且必须 select 回答其中的 3 个。 所以我有一组 7 个虚拟变量,如果受访者 select 回答了答案,则编码为 1,否则编码为 0。

a1 a2 a3 a4 a5 a6 a7
0  0  1  1  0  1  0
1  1  1  0  0  0  0
0  1  0  0  1  0  1

我想将这些虚拟变量转换回三个变量,每个变量都包含给定的答案。那是这样的:

choice1 choice2 choice3
 a3       a4      a6
 a1       a2      a3
 a2       a5      a6

我尝试在整组“a”变量上使用 tidyverse“收集”

int <- old_df %>%  mutate_at(vars(a1:a7), ~ ifelse(. == 0, NA, .))
new <- int %>% gather("choice1", "present", a1:a7, na.rm = TRUE)

但是,我没有得到我想要的结果,因为我只有 1 个变量,包含所有可能的“a”答案。

我还尝试对每个“a”变量使用“gather”,但我还是没有得到我想要的,因为我最终复制了原始数据集(使用字符串变量而不是 1 和 0)。

知道吗,我怎样才能得到我想要的那种数据?

非常感谢!

df_old <- read.table(text = "a1 a2 a3 a4 a5 a6 a7
0  0  1  1  0  1  0
1  1  1  0  0  0  0
0  1  0  0  1  0  1", header = T)

df_old %>% mutate(rowid = row_number()) %>%
  pivot_longer(!rowid) %>%
  filter(value != 0) %>%
  group_by(rowid) %>%
  mutate(choice = paste0('choice', seq_len(max(rowSums(df_old))))) %>%
  pivot_wider(id_cols = rowid, names_from = choice, values_from = name) %>%
  select(-rowid)

# A tibble: 3 x 4
# Groups:   rowid [3]
  rowid choice1 choice2 choice3
  <int> <chr>   <chr>   <chr>  
1     1 a3      a4      a6     
2     2 a1      a2      a3     
3     3 a2      a5      a7  

这在 base R

中会容易得多
out <- as.data.frame(t(apply(df1, 1, function(x) names(x)[x == 1])))
names(out) <- paste0('choice', seq_along(out))

-输出

out
#  choice1 choice2 choice3
#1      a3      a4      a6
#2      a1      a2      a3
#3      a2      a5      a7

数据

df1 <- structure(list(a1 = c(0L, 1L, 0L), a2 = c(0L, 1L, 1L), a3 = c(1L, 
1L, 0L), a4 = c(1L, 0L, 0L), a5 = c(0L, 0L, 1L), a6 = c(1L, 0L, 
0L), a7 = c(0L, 0L, 1L)), class = "data.frame", row.names = c(NA, 
-3L))