【问题标题】:Reshape data from long to semi-wide in R在R中将数据从长重塑为半宽
【发布时间】:2011-06-13 17:41:18
【问题描述】:

我有数据,其中每个参与者对 9 个对象(27 个判断)中的每个对象做出 3 个判断。这 9 个对象在 3x3 设计中各不相同(在受试者内),因此有 2 个因素。

我从 ID + 27 个数据列开始,我需要有

  • 身份证
  • 2 个因素列:性能、情况
  • 3 个值列:Success、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
...

谢谢!

【问题讨论】:

    标签: r dataframe reshape


    【解决方案1】:

    试试这个:

    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,但实际上,这个公式是我真正需要的。既然你做到了,它当然看起来很明显。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多