You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R语言中将宽表转长表:评分者信度数据集重构问题

解决评分者信度数据集的格式转换问题

你的需求是把原始“单评分者对应多项目”的结构,转成“单项目对应多评分者”的结构,只用pivot_longer确实不够,需要结合pivot_wide来完成,以下是具体实现步骤:

1. 加载依赖包

首先确保你安装并加载了tidyverse:

library(tidyverse)

2. 数据转换代码

假设你的原始数据框名为df,执行以下代码即可完成转换:

# 模拟你的原始数据(如果已有数据可跳过这步)
df <- tibble(
  Subject = c("AB", "AB", "CD", "CD", "EF", "EF"),
  Rater = c(1, 2, 1, 2, 1, 2),
  Item_1 = c(6, 5, 4, 6, 4, 7),
  Item_2 = c(4, 5, 5, 5, 4, 5)
)

# 核心转换逻辑
result <- df %>%
  # 第一步:把多Item列转成长格式,拆分出Item编号和对应分数
  pivot_longer(
    cols = starts_with("Item_"),
    names_to = "Item",
    values_to = "Score"
  ) %>%
  # 提取Item里的数字(把Item_1转成1,Item_2转成2)
  mutate(Item = parse_number(Item)) %>%
  # 第二步:把Rater转成宽格式,生成Rater_1/Rater_2列
  pivot_wider(
    names_from = Rater,
    values_from = Score,
    names_glue = "Rater_{Rater}"
  )

# 查看转换结果
print(result)

3. 代码逻辑说明

  • pivot_longer:将Item_1/Item_2这类宽格式的项目列,拆分成Item(项目编号)和Score(对应分数)两列,先完成“项目维度”的长格式转换。
  • mutate(Item = parse_number(Item)):把Item列的文本前缀去掉,只保留数字,匹配目标结构的Item列格式。
  • pivot_wider:将Rater列的1/2作为新列名,对应的Score作为列值,通过names_glue给列名加上Rater_前缀,最终得到你需要的双评分者列结构。

转换后结果

运行代码后得到的结果和你期望的结构完全一致:

# A tibble: 6 × 4
  Subject Item  Rater_1 Rater_2
  <chr>   <dbl>    <dbl>    <dbl>
1 AB          1        6        5
2 AB          2        4        5
3 CD          1        4        6
4 CD          2        5        5
5 EF          1        4        7
6 EF          2        4        5

内容的提问来源于stack exchange,提问作者B.Nin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:15:34