【发布时间】: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