Create columns from factors and count [duplicate]

You only need to make some slight modification to your code. You should use .(Name) instead of c("Name"):

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

gives:

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

Other possibilities include:

1. table(df1) as @alexis_laz mentioned in the comments, this gives:

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

2. The dcast function of the reshape2 package (or data.table which has the same dcast function):

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

gives:

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

Leave a Comment