8

I have a data frame which contains a customerid, and a list. I would like to merge those list pertaining to the same customer.

library(plyr)
subsets <- list(c("a", "d", "e"), c("a", "b", "c", "e"))
customerids <- c(1,1)
transactions <- data.frame(customerid = customerids,subset =I(subsets))
> transactions
  customerid     subset
1          1    a, d, e
2          1 a, b, c, e

If I want to merge the subsets with ddply, I get an expanded result

> ddply(transactions, .(customerid), summarise, subset=Reduce(union,subset))
  customerid subset
1          1   a
2          1   d
3          1   e
4          1   b
5          1   c

while I would have expected all the results in 1 row.

lokheart
  • 22,255
  • 36
  • 92
  • 166
nicolas
  • 9,269
  • 3
  • 35
  • 76
  • 1
    The step creating the dataframe throws an error. You probably created this differently and should post `dput(transactions)`. I don't think dataframes hold list objects very well. There's a well-known difficulty with POSIXlt objects in dataframes as well. – IRTFM Jul 15 '13 at 21:25
  • indeed I copied a wrong input( no I operator), this is fixed. – nicolas Jul 15 '13 at 21:28
  • +1 for the `I` creating the list element within the data.frame. – agstudy Jul 15 '13 at 21:30
  • @agstudy, that was his [earlier question](http://stackoverflow.com/q/17662596/559784) today. – Arun Jul 15 '13 at 21:32
  • @Arun I see...so +1 for you also! – agstudy Jul 15 '13 at 21:33
  • @nicolas I would transform, my data to a list in this case `by(transactions$subset,transactions$customerid,unlist)` – agstudy Jul 15 '13 at 21:39

1 Answers1

4

You can do something like this:

ddply(transactions, .(customerid), function(x) 
            data.frame(subset=I(list(unlist(x$subset)))))

Edit: I'm not sure I follow your comments. But if you want just unique values within each customerid for subset then:

ddply(transactions, .(customerid), function(x) 
            data.frame(subset=I(list(unique(unlist(x$subset))))))
Arun
  • 113,200
  • 24
  • 277
  • 373