如何将宽数据转换为交叉分类模型的长格式 [R, GLMM]

How to convert a wide data into long format for cross-classified model [R, GLMM]

我想在R中将宽数据转换为长数据,我的数据集用于交叉分类模型,探索参与者对具有不同特征的每个目标项目的反应。

虽然从宽到长的转换教程很多,但我找不到专门解释交叉分类模型转换的教程。

为了保持一致性,我想尽可能使用 tidyverse

我的示例数据如下:

structure(list(item_name = c("x1", "x2", "participant_id", "1", 
"2", "3", "4", "5", "6", "7"), participant_variable_1 = c(NA, 
NA, NA, 20, 23, 21, 20, 19, 22, 30), condition = c(NA, NA, NA, 
"A", "B", "A", "B", "A", "B", "A"), t1.item1.test1 = c(1, 3, 
NA, 0, 1, 0, 1, 0, 0, 1), t1.item2.test1 = c(2, 2, NA, 0, 0, 
0, 1, 1, 0, 1), t1.item3.test1 = c(1, 3, NA, 0, 0, 0, 1, 0, 0, 
0), t1.item4.test1 = c(3, 1, NA, 1, 0, 0, 0, 1, 1, 0), t2.item1.test1 = c(1, 
3, NA, 0, 1, 1, 0, 1, 1, 1), t2.item2.test1 = c(2, 2, NA, 1, 
0, 1, 0, 1, 0, 1), t2.item3.test1 = c(1, 3, NA, 0, 0, 0, 1, 0, 
0, 0), t2.item4.test1 = c(3, 1, NA, 1, 1, 0, 1, 1, 1, 0), t1.item1.test2 = c(1, 
3, NA, 0, 1, 0, 1, 0, 0, 1), t1.item2.test2 = c(2, 2, NA, 0, 
0, 0, 1, 1, 0, 1), t1.item3.test2 = c(1, 3, NA, 0, 0, 0, 1, 0, 
0, 0), t1.item4.test2 = c(3, 1, NA, 1, 0, 0, 0, 1, 1, 0), t2.item1.test2 = c(1, 
3, NA, 0, 1, 1, 0, 1, 1, 1), t2.item2.test2 = c(2, 2, NA, 1, 
0, 1, 0, 1, 0, 1), t2.item3.test2 = c(1, 3, NA, 0, 0, 0, 1, 0, 
0, 0), t2.item4.test2 = c(3, 1, NA, 1, 1, 0, 1, 1, 1, 0)), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

我想要一个长数据,如下所示:

请多多指教!

这个答案需要在 tidyr 的开发版本中大量使用新的 pivot_ 函数。如果你愿意 运行 开发版本,你可以使用 devtools::install_github("tidyverse/tidyr") 安装它。

首先,我们将数据分成项目和参与者信息 - 将两者存储在同一个 table:

中实际上并没有任何好处
item_info = dat[1:2, ]
participant_info = dat[4:nrow(dat), ] %>%
    rename(participant_id = item_name)

那么是时候进行大量的调整了:

# I have the dev version of tidyr so that is being loaded
library(tidyverse)

item_long = item_info %>%
    select(-participant_variable_1, -condition) %>%
    pivot_longer(
        cols = t1.item1:t2.item4,
        names_to = c("time", "item"),
        names_pattern = "t(\d)\.(item\d)",
    ) %>%
    pivot_wider(names_from = item_name, values_from = value)

participant_long = participant_info %>%
    pivot_longer(
        cols = t1.item1:t2.item4,
        names_to = c("time", "item"),
        names_pattern = "t(\d)\.(item\d)",
        values_to = "response"
    )

combined = participant_long %>%
    left_join(item_long, by = c("item", "time"))

结果:

> combined
# A tibble: 56 x 8
   participant_id participant_variable_1 condition time  item  response    x1    x2
   <chr>                           <dbl> <chr>     <chr> <chr>    <dbl> <dbl> <dbl>
 1 1                                  20 A         1     item1        0     1     3
 2 1                                  20 A         1     item2        0     2     2
 3 1                                  20 A         1     item3        0     1     3
 4 1                                  20 A         1     item4        1     3     1