【问题标题】:How to reconstruct a categorical variable with multiple choices如何重建具有多个选择的分类变量
【发布时间】:2023-03-09 01:13:01
【问题描述】:

我有以下问题。我正在分析问卷中的数据,其中向受访者提供了 7 个可能的答案,并且必须选择其中的 3 个。 所以我有一组 7 个虚拟变量,如果受访者选择了答案,则编码为 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 “gather”

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)。

任何想法,我怎样才能获得我想要的数据?

非常感谢!

【问题讨论】:

    标签: r dummy-variable gather


    【解决方案1】:
    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  
    

    【讨论】:

    • 谢谢!这几乎行得通。但是我在使用 mutate 和 paste 时收到一条错误消息。消息如下:“mutate() 输入 choice 出现问题。x 输入 choice 无法回收到大小 3。错误发生在组 1:rowid = 1。”如果我手动设置重复次数(而不是使用“max(RowSums())”,对于不同的“rowid”,我会得到相同的错误。知道为什么吗?
    • 作为跟进:我想我知道问题所在:一些代表只选择了 2 个而不是 3 个选项,因此一些“rowid”组无法“适应”新创建的 varialbe“选择”预设重复次数
    • 解决了! df_old %>% mutate(rowid = row_number()) %>% pivot_longer(!rowid) %>% filter(value != 0)%>% group_by(rowid) %>% mutate(choice = row_number())%> % pivot_wider(id_cols = rowid, names_from = choice, values_from = name) %>% select(-rowid)
    【解决方案2】:

    这在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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 2020-08-04
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-04
      相关资源
      最近更新 更多