I have a dataframe of the following form:
df <- data.frame(client = c("client1", "client1", "client2", "client3", "client3"), product = c("A", "B", "A", "D", "A"), purchase_Date = c("2010-03-22", "2010-02-02", "2009-03-02", "2011-04-05", "2012-11-01")) df$purchase_Date <- as.Date(df$purchase_Date, format = "%Y-%m-%d")
which is as follows:
client product purchase_Date 1 client1 A 2010-03-02 2 client1 B 2010-02-02 3 client2 A 2009-03-02 4 client3 D 2011-04-05 5 client3 A 2012-11-01
which I would like to change as follows:
client purchase1 purchase2 1 client1 BA 2 client2 A <NA> 3 client3 DA
therefore, I would like to know which product was the first, second, third, etc., each person ordered by the date of purchase. I can easily get each individually using data.table:
library(data.table) setDT(df)[ , .SD[order(-purchase_Date), product][1], by = client]
for the first one. but I have no idea how to effectively get the desired result.