2017-03-17 2 views
0

Ich habe eine Tabelle wieTransaktionsliste in den Warenkorb Daten

ID Productpurchased Year 
1A   Abc   2011 
1A   Abc   2011  
1A   xyz   2011 
1A   Abc   2012 
2A   bcd   2013 
2A   Abc   2013 

Ausgabe erforderliches Format

ID  Purchase basket  Year  Abc-count xyz-count bcd-count  
1A  (Abc,xyz)   2011  2   1   0 
1A  (Abc)    2012  1   0   0 
2A  (bcd , Abc)   2013  1   0   1 
+0

Ihre ursprüngliche Frage mit den Daten als Text, nicht Bilder, war besser. – neilfws

+0

'Bibliothek (dplyr); df%>% group_by (ID, Jahr)%>% zusammenfassen (basket = toString (unique (Produkteinkauf)), Abc = Summe (Produkteinkauf == 'Abc'), bcd = Summe (Produkteinkauf == 'bcd'), xyz = sum (Productpurchased == 'xyz')) ' – alistaire

+0

oder programmgesteuert,' library (tidyverse); df%>% group_by (ID, Jahr)%>% zusammenfassen (basket = toString (unique (Productpurchased)), tab = Liste (Tabelle (Productpurchased)), vars = map (Tab, Namen))%>% unnest() %>% spread (vars, tab) ' – alistaire

Antwort

1

wir dies mit data.table leicht tun können. Konvertieren Sie den 'data.frame' in 'data.table' (setDT(df1)), gruppiert nach 'ID', 'Year', paste die unique Elemente von 'Productpurchased' und weisen Sie ihn zu (:=), um 'Purchase_basket' Spalte zu erstellen, dann dcast von ‚langen‘ auf ‚breit‘ als die fun.aggregatelength

library(data.table) 
dcast(setDT(df1)[, Purchase_basket := toString(unique(Productpurchased)),.(ID, Year)], 
     ID + Year + Purchase_basket ~paste0(Productpurchased, ".count"), length) 
# ID Year Purchase_basket Abc.count bcd.count xyz.count 
#1: 1A 2011  Abc, xyz   2   0   1 
#2: 1A 2012    Abc   1   0   0 
#3: 2A 2013  bcd, Abc   1   1   0 
+0

Super einfach! Danke :) @akrun – Pb89

0

genau die gleiche Logik wie data.table jedoch unter Verwendung von dplyr angibt.

df_2 <- read.table(text = 'ID Productpurchased Year 
1A   Abc   2011 
1A   Abc   2011  
1A   xyz   2011 
1A   Abc   2012 
2A   bcd   2013 
2A   Abc   2013', 
header = TRUE, stringsAsFactors = FALSE) 



df_2 %>% group_by(ID, Year) %>% 
    mutate(Abc_count=grepl("Abc", Productpurchased), 
     bcd_count=grepl("bcd", Productpurchased), 
     xyz_count=grepl("xyz", Productpurchased)) %>% 
    summarise(Productpurchased = paste("(", paste(unique(Productpurchased), collapse = ","),")", sep=""), 
      Abc_count=sum(Abc_count), 
      bcd_count=sum(bcd_count), 
      xyz_count=sum(xyz_count)) 
Verwandte Themen