请求指导:在R语言中完成pre-test与post-test数据配对
解决方案
这里提供两种常用工具的实现方法,帮你把长格式的测试数据转换为宽格式的配对数据:
使用 R(tidyverse 包)
如果你用 R 处理数据,tidyr 包的 pivot_wider() 函数可以轻松完成转换:
# 加载 tidyverse 包(未安装先运行 install.packages("tidyverse")) library(tidyverse) # 构建示例数据框(替换成你自己的数据集即可) test_data <- data.frame( Test = c("pretest", "posttest", "pretest", "pretest", "posttest", "pretest", "posttest", "posttest"), Participant_ID = c("part001", "part001", "part002", "part003", "part002", "part004", "part003", "part004"), Score = c(50, 70, 40, 40, 85, 60, 65, 75) ) # 转换为宽格式 wide_data <- test_data %>% pivot_wider( id_cols = Participant_ID, # 按参与者ID分组 names_from = Test, # 把Test列的取值作为新列名 values_from = Score # 把Score列的值填充到对应新列 ) %>% arrange(Participant_ID) # 按参与者ID排序(可选) print(wide_data)
运行后得到的结果:
# A tibble: 4 × 3 Participant_ID pretest posttest <chr> <dbl> <dbl> 1 part001 50 70 2 part002 40 85 3 part003 40 65 4 part004 60 75
使用 Python(pandas 库)
如果用 Python 处理,pandas 的 pivot() 方法可以实现同样效果:
import pandas as pd # 构建示例数据框(替换成你自己的数据集即可) data = { "Test": ["pretest", "posttest", "pretest", "pretest", "posttest", "pretest", "posttest", "posttest"], "Participant_ID": ["part001", "part001", "part002", "part003", "part002", "part004", "part003", "part004"], "Score": [50, 70, 40, 40, 85, 60, 65, 75] } df = pd.DataFrame(data) # 转换为宽格式 wide_df = df.pivot( index="Participant_ID", columns="Test", values="Score" ).reset_index() # 调整列名格式(让结果完全匹配你的需求) wide_df.columns.name = None wide_df = wide_df[["Participant_ID", "pretest", "posttest"]].rename( columns={"pretest": "Pretest", "posttest": "Posttest"} ) print(wide_df)
输出结果:
Participant_ID Pretest Posttest 0 part001 50 70 1 part002 40 85 2 part003 40 65 3 part004 60 75
内容的提问来源于stack exchange,提问作者Faisal Mustafa
相关产品推荐
相关产品推荐

