代码之家  ›  专栏  ›  技术社区  ›  Varun

R编码通过分隔符连接的分类变量

  •  0
  • Varun  · 技术社区  · 7 年前

    上下文

    在我的数据框中,我有一个专栏,其中包含了对餐馆消费替代品问题的固定回答。受访者可以选择 倍数 如果需要,请立即选择。

    #Unique responses to question
    unique_vector = c('Bring food from home',
                      'Buy from a supermarket',
                      'Buy from deli, bakery, coffee, or sandwich shop',
                      'Go home',
                      'Go out to a fast food outlet',
                      'Order food from outside',
                      'Snack between meals',
                      'Go out to a full service restaurant',
                      'Skip the meal')
    

    在对10名受访者进行调查后,得出的数据框架如下所示-

    #Survey Dataframe
    df= data.frame(
                              Id = c(1:10),
    
                              QUESTION=c(unique_vector[1],
                              paste0(unique_vector[1],',',unique_vector[2]),
                              paste0(unique_vector[1],',',unique_vector[2],',',unique_vector[2]),
                              paste0(unique_vector[4],',',unique_vector[5],',',unique_vector[1]),
                              paste0(unique_vector[3],',',unique_vector[1],',',unique_vector[9],',',unique_vector[7]),
                              paste0(unique_vector[5],',',unique_vector[6],',',unique_vector[8],',',unique_vector[1]),
                              unique_vector[3],
                              "",
                              paste0(unique_vector[5],',',unique_vector[6],',',unique_vector[8],',',unique_vector[1]),
                              "")
    )
    

    我的目标

    我想把这个摊开 QUESTION 列,以便

    然后我想 对这些反应进行编码 这样它们被记录为1(没有响应被记录为0)。

    我的尝试

    我试着在R中使用一个热编码包,但我不知道如何修改代码以分离串联的响应。

    #Attempt
    library(onehot)
    encoded_df = onehot(df[,2], stringsAsFactors=TRUE)
    

    1 回复  |  直到 7 年前
        1
  •  1
  •   Paweł Chabros    7 年前

    我怀疑这是最简单的方法,但结果是正确的:

    library(tidyverse)
    
    unique_vector %>%
      str_c(collapse = ')|(') %>%
      str_c('(', ., ')') %>%
      str_extract_all(df$QUESTION, ., simplify = TRUE) %>%
      as.data.frame() %>%
      as_tibble() %>%
      mutate(Id = row_number()) %>%
      gather(x, key, V1:V4) %>%
      mutate(val = 1) %>%
      spread(key, val, fill = 0) %>%
      select(-c(x, V1)) %>%
      group_by(Id) %>%
      summarise_all(~if_else(sum(.) > 0, 1, 0))
    

    如果分离器将不同于 , ( 答案中也会出现)通过在此分隔符上拆分,操作会更简单:

    df %>%
      as_tibble() %>%
      mutate(QUESTION = map(QUESTION, ~str_split(.x, ',')[[1]] %>% unique)) %>%
      unnest() %>%
      mutate(val = 1) %>%
      spread(QUESTION, val, fill = 0) %>%
      select(-V1)