[R] Summieren pro Gruppe?

BaseBallBatBoy

Erfahrenes Mitglied
Hallo!

Ich habe eine Matrix:

ID, Wert
1,50
2,20
2,10

Nun möchte ich eine weitere Spalte haben die pro Gruppe das Total des Wertes hat:

ID, Wert, Total
1, 50, 50
2, 20, 30
2, 10, 30


Hier meine beiden versuche, die leider alle nicht klappen....
my.Matrix <- cbind ( my.Matrix, sum(as.numeric(my.Matrix[my.Matrix[,1]==my.Matrix[,1],2])) )
oder aber das hier:
my.Matrix <- cbind ( my.Matrix, aggregate( my.Matrix[,2], by=list(my.Matrix[,1]), sum))


Hat jemand eine Idee?

Gruss
BBBB
 
habe die lösung, man muss aggregate über zwei zeilen hinweg brauchen:

totals <- aggregate( my.Matrix[,2] , by = list (my.Matrix[,1]), sum)
my.Matrix <- cbind ( my.Matrix, totals[my.Matrix[,1],totals[,1],2])
 

Neue Beiträge

Zurück