从因子和计数创建列

Create columns from factors and count

一个看似简单的问题让我很忙。

我有一个数据框:

> df1
  Name Score
1  Ben     1
2  Ben     2
3 John     1
4 John     2
5 John     3

我想像这样创建 table 的摘要:

> df2
  Name Score_1 Score_2 Score_3
1  Ben       1       1       0
2 John       1       1       1

因此 df2 必须 (i) 仅显示唯一 "Names" 并且 (ii) 根据 "Score" 中的唯一因素创建列,并且 (iii) 计算一个人获得该分数的次数。

我试过了:

df2 <- ddply(df1, c("Name"), summarise
          ,Score_1 = sum(df1$Score == 1)
          ,Score_2 = sum(df1$Score == 2)
          ,Score_3 = sum(df1$Score == 3))

产生:

  Name Score_1 Score_2 Score_3
1  Ben       2       2       1
2 John       2       2       1

所以我的尝试错误地计算了 所有 次出现而不是计算 "per group"

编辑: 根据评论,还尝试了 reshape (可能只是做错了):

> reshape(df1, idvar = "Name", timevar = "Score", direction = "wide")
  Name
1  Ben
3 John

首先,缺少 "Score" 列,但更糟糕的是,根据我对 reshape 的研究,我不相信我会得到 计数每个因素,也就是整点。

我们可以使用dplyr/tidyr

 library(dplyr)
 library(tidyr)
 df1 %>% 
     group_by(Name) %>%
      mutate(n=1, Score= paste('Score', Score, sep='_')) %>% 
      spread(Score, n, fill=0) 
 #     Name Score_1 Score_2 Score_3
 #  (chr)   (dbl)   (dbl)   (dbl)
 #1   Ben       1       1       0
 #2  John       1       1       1

您只需要对您的代码进行一些细微的修改。您应该使用 .(Name) 而不是 c("Name"):

ddply(df1, .(Name), summarise,
      Score_1 = sum(Score == 1),
      Score_2 = sum(Score == 2),
      Score_3 = sum(Score == 3))

给出:

  Name Score_1 Score_2 Score_3
1  Ben       1       1       0
2 John       1       1       1

其他可能性包括:

1. table(df1) 正如@alexis_laz在中提到的,这给出:

> table(df1)
       Score
Name   1 2 3
  Ben  1 1 0
  John 1 1 1

2. reshape2包的dcast函数(或data.table 具有相同的 dcast 功能):

library(reshape2) # or library(data.table)
dcast(df1, Name ~ paste0("Score_", Score), fun.aggregate = length) 

给出:

  Name Score_1 Score_2 Score_3
1  Ben       1       1       0
2 John       1       1       1