2013-10-25 11 views
6

Mam ramki danych, który wygląda tak:wartości Sum ze wspólnym ID w dataframe

df<-data.frame(id=c("xx33","xx33","xx22","xx11","xx11","xx00"),amount=c(10,15,100,20,10,15),date=c("01/02/2013","01/02/2013","02/02/2013","03/03/2013","03/03/2013","04/04/2013")) 

    id amount date 
1 xx33 10 01/02/2013 
2 xx33 15 01/02/2013 
3 xx22 100 02/02/2013 
4 xx11 20 03/03/2013 
5 xx11 10 03/03/2013 
6 xx00 15 04/04/2013 

chcę skompilować wszystkie wspólne identyfikatory i zsumować kwoty, a także liczbę wystąpień identyfikatora, ale również przenosić wspólne informacje, takie jak data, która jest taka sama dla każdego identyfikatora (wraz z każdą inną zmienną). Tak, chcę być wyjście:

id sum date  number 
1 xx33 25 01/02/2013 2 
2 xx22 100 02/02/2013 1 
3 xx11 30 03/03/2013 2 
4 xx00 15 04/04/2013 1 

Próbowałem

ddply(.data = df, .var = "id", .fun = nrow) 

i która zwraca całkowitą liczbę wystąpień, ale nie mogę znaleźć sposób, aby zsumować wszystkie wspólne Id bez pętli.

Odpowiedz

6

Oto rozwiązanie przy użyciu pakietu plyr:

library(plyr) 
ddply(df,.(date,id),summarize,sum=sum(amount),number=length(id)) 
      date id sum number 
    1 01/02/2013 xx33 25  2 
    2 02/02/2013 xx22 100  1 
    3 03/03/2013 xx11 30  2 
    4 04/04/2013 xx00 15  1 
5

Korzystanie z biblioteki data.table -

library(data.table) 
dt <- data.table(df) 
dt2 <- dt[,list(sumamount = sum(amount), freq = .N), by = c("id","date")] 

wyjściowa:

> dt2 
    id  date sumamount freq 
1: xx33 01/02/2013  25 2 
2: xx22 02/02/2013  100 1 
3: xx11 03/03/2013  30 2 
4: xx00 04/04/2013  15 1 
4

Oto roztwór zasady R

> cbind(aggregate(amount~id+date, sum, data=df), table(df$id))[, -4] 
    id  date amount Freq 
1 xx33 01/02/2013  25 1 
2 xx22 02/02/2013 100 2 
3 xx11 03/03/2013  30 1 
4 xx00 04/04/2013  15 2 
3

obowiązkowa podstawa R odpowiedź:

unique(transform(df, amount=ave(amount, id, FUN=sum), 
        count=ave(amount, id, FUN=length))) 
#  id amount  date count 
# 1 xx33  25 01/02/2013  2 
# 3 xx22 100 02/02/2013  1 
# 4 xx11  30 03/03/2013  2 
# 6 xx00  15 04/04/2013  1 
Powiązane problemy