R - 聚合和重新排列

时间:2012-11-21 19:38:10

标签: r

我有以下数据框“myData”

  NAME GAME    STATUS
1 aaa  poker   PASSED
2 bbb  poker   FAILED
3 aaa  tennis  PASSED
4 bbb  tennis  PASSED

我想要以下输出

  NAME  FAILED PASSED TOTAL
1 aaa     0      2      2
2 bbb     1      1      2

我尝试了以下代码

myResult <- as.data.frame(table(myData[,c("NAME","STATUS")]))

上面的代码给了我

  NAME  STATUS   Freq
1 aaa   FAILED   0
2 aaa   PASSED   2
3 bbb   FAILED   1
4 bbb   PASSED   1

此时,我不确定如何旋转“myResult”以我需要的格式获取它。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

这是一个具有基本R功能的解决方案:

myResult <- as.data.frame(unclass(xtabs( ~ NAME + STATUS, myData)))
myResult$TOTAL <- rowSums(myResult)


    FAILED PASSED TOTAL
aaa      0      2     2
bbb      1      1     2

答案 1 :(得分:1)

对于这类事情,我经常使用 reshape2 包中的dcast

dat <- read.table(text = "  NAME GAME    STATUS
1 aaa  poker   PASSED
2 bbb  poker   FAILED
3 aaa  tennis  PASSED
4 bbb  tennis  PASSED",header = TRUE,sep = "",row.names = 1)

library(reshape2)
dcast(dat,NAME~STATUS,
        fun.aggregate = length,
        value.var = "STATUS",
        margins = "STATUS")