Creating columns from factors and counting

Apparently, the simple problem is that I am very busy.

I have a data frame:

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

I would like to create a table summary as follows:

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

So df2 should (i) show only the unique “Names” and (ii) create columns from the unique factors in the “Score” and (iii) count the number of times a person received the specified grade.

I tried:

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

which produces:

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

Thus, my attempt incorrectly takes everything into account , rather than counting "per group"

EDIT: As per the comments, also tried reshape(maybe just wrong):

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

"" , , reshape, , count , .

+4
2

. .(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. dcast reshape2 ( 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
+3

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
+2

Source: https://habr.com/ru/post/1626832/


All Articles