R 将 gather() 用于调查数据中的多个循环

R use gather() for multiple loops in survey data

我正在处理一些有点尴尬的调查数据。调查软件的输出格式为:

Respondent     contact1     contact2     question1     question2     question1     question2
   Tim           Bob          Alan           1             0             0             1

其中:

Contact1 和 contact2 是受访者可以列出他们接触过的个人的位置。

下面的一组固定问题然后针对每个联系人循环,每个都是一个新列。答案仅记录为 1 或 0。

我希望将此数据重塑为更便于分析的布局:

Respondent     Contact    question1    question2
   Tim           Bob          1            0
   Tim           Alan         0            1

显然这是简化的,实际数据集有 100 个联系人和大约 8 个问题,但布局是相同的。

我认为最好的方法是结合使用 gather()、express() 和 spread()

data %>%
  gather(key, value, -Respondent) %>%
  extract(key, c("question", "contact"), "reg ex") %>%
  spread(question, value)

但事实证明,不同的长度和多个触点很难对齐。

"contact" 列中删除数字,然后您可以使用 pivot_longer.

names(df) <- sub('(?<=contact)\d+', '', names(df), perl = TRUE)

tidyr::pivot_longer(df, cols = -Respondent, names_to = '.value')

#  Respondent contact question1 question2
#  <chr>      <chr>       <int>     <int>
#1 Tim        Bob             1         0
#2 Tim        Alan            0         1

数据

df <- structure(list(Respondent = "Tim", contact1 = "Bob", contact2 = "Alan", 
    question1 = 1L, question2 = 0L, question1 = 0L, question2 = 1L), 
   class = "data.frame", row.names = c(NA, -1L))