How to add a column that counts duplicates in sequence?

Viewed 579

I'm looking to add a column to a data frame (integrates2) that counts duplicates in sequence. Below is what the data looks like:

name    program  date of contact   helper column
John     ffp        10/11/2014          2
John     TP         10/27/2014          2
Carlos   TP         11/19/2015          3
Carlos   ffp        12/1/2015           3
Carlos   wfd        12/31/2015          3
Jen      ffp        9/9/2014            2
Jen      TP         9/30/2014           2    

This is a list of people who've attended certain programs on certain dates. I've added a helper column to count duplicates and sorted the date of contact. I am looking to count the combinations of programs that exist (e.g. ffp-tp, tp-ffp-wfd).

In order to do this I want to implement the following code in order to transpose the ordered combinations with the help of a new column named "program2":

 #transpose the programs 
 require(reshape2) dcast(integrates2, name ~ program2, value.var=”program”)

Then I plan to use the following code to turn the result into a table and data frame and count frequencies:

 res = table(integrates2)
 resdf = as.data.frame(res)

I saw this used in the following link: Count number of time combination of events appear in dataframe columns ext

What I need from "program2" is to look like this:

  Name    program  date of contact   helper column   program2
  John     ffp        10/11/2014          2             1
  John     TP         10/27/2014          2             2
  Carlos   TP         11/19/2015          3             1
  Carlos   ffp        12/1/2015           3             2
  Carlos   wfd        12/31/2015          3             3

This way, I can use "program2" to transpose into different columns and then count the combinations. The final result should look something like this:

    program  pro1   pro2   freq      
     ffp     tp             2   
     TP      ffp    wfd     1    

I'm sure there are easier ways to do this, but as I am learning, this is where I am. Appreciate the help guys!

2 Answers
Related