在R中将数据从长格式转换为半宽格式

3
我有一些数据,每个参与者对9个对象进行了3次评价(共27次评价)。这9个对象采用了3x3设计(在受试者内),因此有2个因素。
我现在有ID和27个数据列,我需要:
- ID - 2个因素列:表现,情境 - 3个值列:成功,ProbAdmit,Admit
我已经阅读了reshape()、melt()和cast()的手册,但还没有找到实现目标的方法。以下是我的当前进展,您可以从中看到我的实际数据。
scsc3 <- read.csv("http://swift.cbdr.cmu.edu/data/SCSC3-2006-10-10.csv")
library(reshape)
scsc3.long <- melt(scsc3,id="Participant")
scsc3.long <- cbind(scsc3.long,colsplit(scsc3.long$variable,split="[.]",names=c("Item","Candidate","Performance","Situation")))
scsc3.long$variable <- NULL
scsc3.long$Candidate <- NULL

以上代码让我得到了这个结果:
Participant  value  Item      Performance  Situation
4001         5.0    Success   GL           IL
4001         60     ProbAdmit GL           IL
4001         1      Admit     GL           IL
4002         ....

我需要的是这样的数据框架。
Participant Performance  Situation SuccessValue ProbAdmitValue AdmitValue
4001        GL           IL        5.0          60             1
...

谢谢!

1个回答

9

试试这个:

require(reshape2)
> dcast(scsc3.long, 
        Participant + Performance + Situation ~ Item, 
        value_var = 'value' )

  Participant Performance Situation Admit ProbAdmit Success
1        4001          GH        IH     1       100       7
2        4001          GH        IL     1        50       5
3        4001          GH        IM     1        60       5
4        4001          GL        IH     0        40       3
5        4001          GL        IL     0         0       2
6        4001          GL        IM     0        40       4
...

可以这样理解dcast的功能:将数据框转换为宽格式,其中行是Participant + Performance + Situation的组合,列是Item的不同可能值,即Admit, ProbAdmit, Successvalue_var = 'value'指示应为每个“行-列”组合显示value列的条目。


太好了!谢谢你!我还没有发现reshape2或dcast,但是公式确实是我所需要的。现在你做到了,当然看起来很明显。谢谢! - Sam Swift

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接