重组 r: reshape, dcast 中的数据,融化...似乎对这个数据框没有任何作用

标签 r

这是我导入的数据框的前几行的示例(在完整数据集中,主题变量共有五个级别/因子,另外两个是代数 II 和几何)。

SID   firstName lastName    subject       sumScaleScore sumPerformanceLevel
604881  JIM     Ro          Mathematics   912           2
604881  JIM     Ro          ELA           964           4
594181  JERRY   Chi         ELA           997           1
594181  JERRY   Chi         Mathematics   918           3
564711  KILE    Gamma       ELA           933           5
564711  KILE    Gamma       Algebra I     1043          7

我想将它从上面的长格式(每个人有两行)重组为宽格式(每个人有一行)。例如,新数据的第一行将包含:
SID  firstName  lastName  sumScaleScore_Mathematics  sumPerformanceLevel_Mathematics  sumScaleScore_ELA  sumPerformanceLevel_ELA
604881 JIM      Ro        912                        2                                964                4

我已经尝试过 reshape2 的melt、dcast 和其他一些软件包以及阅读一些帮助文件,但是我的编码并没有削减它。 SPSS 使用“casestovars”很容易做到这一点,但我是 r 的新手并且没有运气。有任何想法吗?

最佳答案

melt 使用前四列,然后使用 dcast :

library(reshape2)
m <- melt(DF, id = 1:4)
dcast(m, SID + firstName + lastName ~...)

给予:
     SID firstName lastName AlgebraI_sumScaleScore AlgebraI_sumPerformanceLevel
1 564711      KILE    Gamma                   1043                            7
2 594181     JERRY      Chi                     NA                           NA
3 604881       JIM       Ro                     NA                           NA
  ELA_sumScaleScore ELA_sumPerformanceLevel Mathematics_sumScaleScore
1               933                       5                        NA
2               997                       1                       918
3               964                       4                       912
  Mathematics_sumPerformanceLevel
1                              NA
2                               3
3                               2

注意: 我们使用了这个输入:
Lines <- "SID   firstName lastName    subject       sumScaleScore sumPerformanceLevel
604881  JIM     Ro          Mathematics   912           2
604881  JIM     Ro          ELA           964           4
594181  JERRY   Chi         ELA           997           1
594181  JERRY   Chi         Mathematics   918           3
564711  KILE    Gamma       ELA           933           5
564711  KILE    Gamma       AlgebraI     1043          7"
DF <- read.table(text = Lines, header = TRUE, as.is = TRUE)

关于重组 r: reshape, dcast 中的数据,融化...似乎对这个数据框没有任何作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34444703/

相关文章:

r - 如何将 xpath 传递给 html_nodes()?

r - 使用整洁的方法将命名列表列表转换为数据帧

r - 创建一个列以指示其他列中存在一个值

在 R 中使用多线程运行 shell 脚本

r - 来自 read.csv 的数据摘要的水平 xtable

r - 在 R 中自定义图形

r - 创建新变量

r - 根据条件创建序列计数器

r - 提取在单个列中找到的数据元素

在 ggplotly() 中保留图例和方形纵横比