【发布时间】:2015-12-08 14:09:24
【问题描述】:
我正在使用基础 R 中的 reshape 函数将用于重复测量设计的长格式数据帧转换为宽格式。请参阅下面的玩具数据集。问题 1、2 和 3 是对三项调查的个人回答。有四名参与者,每人参加四次调查。
Q1 <- c(2,6,5,4,3,8,9,2,1,5,4,7,3,7,2,1)
Q2 <- c(4,7,6,3,1,2,5,6,7,5,4,3,5,6,6,3)
Q3 <- c(7,9,3,1,5,3,7,5,3,3,5,7,8,9,9,3)
Participant <- rep(c("Bob","Sue","Jim","Tom"), times = 1, each = 4)
Time <- rep(c("FirstSurvey","SecondSurvey","ThirdSurvey","FourthSurvey"), times = 4)
m <- as.data.frame(cbind(Participant, Time, Q1, Q2, Q3))
这会产生以下数据框
m
Participant Time Q1 Q2 Q3
1 Bob FirstSurvey 2 4 7
2 Bob SecondSurvey 6 7 9
3 Bob ThirdSurvey 5 6 3
4 Bob FourthSurvey 4 3 1
5 Sue FirstSurvey 3 1 5
6 Sue SecondSurvey 8 2 3
7 Sue ThirdSurvey 9 5 7
8 Sue FourthSurvey 2 6 5
9 Jim FirstSurvey 1 7 3
10 Jim SecondSurvey 5 5 3
11 Jim ThirdSurvey 4 4 5
12 Jim FourthSurvey 7 3 7
13 Tom FirstSurvey 3 5 8
14 Tom SecondSurvey 7 6 9
15 Tom ThirdSurvey 2 6 9
16 Tom FourthSurvey 1 3 3
如果你这样重塑它:
mReshaped <- reshape(m, idvar = "Participant", timevar = "Time", direction = "wide", sep = "", new.row.names = c(1,2,3,4))
它产生以下宽格式数据帧:
mReshaped
Participant Q1FirstSurvey Q2FirstSurvey Q3FirstSurvey Q1SecondSurvey Q2SecondSurvey
1 Bob 2 4 7 6 7
2 Sue 3 1 5 8 2
3 Jim 1 7 3 5 5
4 Tom 3 5 8 7 6
Q3SecondSurvey Q1ThirdSurvey Q2ThirdSurvey Q3ThirdSurvey Q1FourthSurvey Q2FourthSurvey
1 9 5 6 3 4 3
2 3 9 5 7 2 6
3 3 4 4 5 7 3
4 9 2 6 9 1 3
Q3FourthSurvey
1 1
2 5
3 7
4 3
具有以下列名称
colnames(mReshaped)
[1] "Participant" "Q1FirstSurvey" "Q2FirstSurvey" "Q3FirstSurvey" "Q1SecondSurvey"
[6] "Q2SecondSurvey" "Q3SecondSurvey" "Q1ThirdSurvey" "Q2ThirdSurvey" "Q3ThirdSurvey"
[11] "Q1FourthSurvey" "Q2FourthSurvey" "Q3FourthSurvey"
如您所见,当数据框被重塑时,重塑函数将时间变量作为后缀添加到每个重复测量的列名称中。
有谁知道reshape函数中是否有一个参数允许您选择将Time变量作为前缀,在每个Value变量名称的前面?
【问题讨论】: