【问题标题】:R Encoding categorical variables joined by separatorR编码由分隔符连接的分类变量
【发布时间】:2019-02-06 10:49:28
【问题描述】:

背景

在我的数据框中,我有一列包含对餐厅消费替代品问题的固定回复。如果需要,受访者可以一次选择多个选项。

这里有 9 个独特的答案选项可供受访者回答这个问题 -

#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 中使用 one-hot 编码包。但我无法弄清楚如何修改我的代码以分离串联响应。

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

我们将不胜感激。

【问题讨论】:

    标签: r one-hot-encoding


    【解决方案1】:

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

    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)
    

    【讨论】:

    • 反响很好。只是对于包含多个逗号的答案值之一,代码将其拆分为不同的部分Buy from deli, bakery, coffee, or sandwich shop
    • 在第二个答案中 - 是的。我提到过。但在第一个解决方案中它没有。
    猜你喜欢
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    相关资源
    最近更新 更多