Peter
Peter

Reputation: 31

Create sequence pattern in R

I have this dataframe.

 id Trans_Date  Item
100  11/3/2013     A
100  11/3/2013     B
100  18/3/2013     A
101  17/3/2013     C
101  21/3/2013     B
103  12/3/2013     D
103  14/3/2013     A

from this dataframe

i need to get below sequencial dataset.

 id  Item
100 A,B,A
101   C,B
103   D,A

How to do it in R? Using arulesSequence package or other method?

Please help me friends. Thanks in Advance...

Upvotes: 2

Views: 128

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

You could group by id then use toString(). Here is a base R solution:

aggregate(Item ~ id, df, toString)
#    id    Item
# 1 100 A, B, A
# 2 101    C, B
# 3 103    D, A

Or with data.table:

library(data.table)
as.data.table(df)[, toString(Item), by = id]
    id      V1
# 1: 100 A, B, A
# 2: 101    C, B
# 3: 103    D, A

Or if you prefer dplyr:

library(dplyr)
summarise(group_by(df, id), Item = toString(Item))
# Source: local data frame [3 x 2]
#
#      id    Item
#   (int)   (chr)
# 1   100 A, B, A
# 2   101    C, B
# 3   103    D, A

Upvotes: 3

Related Questions