Convert from Single/Stack to Basket

482 views Asked by At

Firstly, I saw a posting for a conversion from basket to single but not the reverse, and I saw another, similar posting that was never answered.

I have data in stack form like so:

ID  Product
A    Prod1
A    Prod2
B    Prod1
B    Prod2
B    Prod3
C    Prod1

I need it to look like this:

ID   Products
A    Prod1, Prod2
B    Prod1, Prod2, Prod3
C    Prod1

I tried unstack then unlist but those didn't work.

How do you convert from single to basket?

2

There are 2 answers

0
A5C1D2H2I1M1N2O1R2T1 On BEST ANSWER

Picking up where @MrFlick left off, if you want to convert your rows to columns, you can do so, but you'll need to add a "time" variable to your data first. This is easily done with getanID from my "splitstackshape" package.

From there, you can use your preferred method to go from a "long" dataset to a "wide" one. For instance, here I've shown how to use the reshape function from base R and dcast.data.table from the "data.table" package:

library(splitstackshape)
reshape(getanID(mydf, "ID"), direction = "wide", idvar = "ID", timevar = ".id")
#    ID Product.1 Product.2 Product.3
# 1:  A     Prod1     Prod2        NA
# 2:  B     Prod1     Prod2     Prod3
# 3:  C     Prod1        NA        NA
dcast.data.table(getanID(mydf, "ID"), ID ~ .id, value.var = "Product", fill = "")
#    ID     1     2     3
# 1:  A Prod1 Prod2      
# 2:  B Prod1 Prod2 Prod3
# 3:  C Prod1          
6
MrFlick On

If you just want to collapse into strings, try

aggregate(Product~ID, dd, paste)

(assuming your data.frame is named dd). That will return

#   ID             Product
# 1  A        Prod1, Prod2
# 2  B Prod1, Prod2, Prod3
# 3  C               Prod1