0

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

在此处输入图像描述

  • condition是参与者被分配到的两个条件之一。
  • 参与者接受了两次测试:t1t2
  • 至于项目级预测变量,x1x2, 被编码。
  • 至于response,参与者对项目的反应是对还是错被编码。
  • 管理了两种test格式,test1test2.

尽管有很多关于从宽到长转换的教程,但我找不到专门解释交叉分类模型转换的教程。

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"))

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

在此处输入图像描述

请并感谢您的指导!

4

1 回答 1

2

这个答案需要大量pivot_使用tidyr. devtools::install_github("tidyverse/tidyr")如果您愿意运行开发版本,则可以安装它。

首先,我们将数据拆分为项目和参与者信息——将两者存储在同一个表中并没有真正获得任何好处:

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
于 2019-07-10T23:38:24.207 回答