-1

I have a seemingly simple problem that I need to solve, however, I can't seem to figure out a fast, simple effective solution to it. A df that I am dealing with looks like this:

ID   type
11   payment
11   contact
11   endorse
12   payment
12   contact
13   endorse

What I am trying to achieve with my code is for each unique ID, how many types it corresponds to and what are they. So, it would look something like:

ID   n_type    what_types
11   3         payment, contact, endorse
12   2         payment, contact
13   1         endorse

Could someone please assist me in this problem?

Thank you so much.

billydh
  • 975
  • 11
  • 27
  • 2
    `library(dplyr);df %>% group_by(ID) %>% summarise(n_type = n(), what_type = toString(type))`. Also, `aggregate(type~ID, df, function(x) c(n_type = length(x), what_type = toString(x)))` and many other base R and `data.table` variants. – Ronak Shah Sep 19 '17 at 07:19

1 Answers1

1

A concise and fast option is data.table:

library(data.table)
setDT(df)[,.(n_type = .N, what_types = .(type)), "ID"]
#   ID n_type              what_types
#1: 11      3 payment,contact,endorse
#2: 12      2         payment,contact
#3: 13      1                 endorse
mtoto
  • 23,919
  • 4
  • 58
  • 71