1

Could you help me performing an aggregation in R? I have the following data:

id<-c("1", "2", "3", "4", "5", "6", "7", "7", "7", "7")
type<-c("a", "a", "b", "b", "b", "b", "c", "c", "c", "c")
weight<-c(1, 2, 1, 2, 3, 4, 1, 2, 3, 4)
time<-c(1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
bd<-cbind(id, type, weight, time)

I need to aggregate "time" and "weight" by "id". Therefore, the first six lines would remain the same, but the 7th line of "bd" would be: id 7; type c; weight: 10; time: 12. The 7th line would be the last in bd.

I will appreciate very much your help.

Andres H
  • 15
  • 6
  • 1
    `bd<-data.frame(id, type, weight, time)` and `result <- aggregate(cbind(time, weight)~id, bd, sum)` – Ronak Shah Nov 09 '20 at 04:11
  • Thank you very much, Ronak for your help! The suggested code performs the aggregation very well. However, the column that is not aggregated ("type") is dropped from the new data frame ("result"). Is there a way to keep "type" in the data frame when performing aggregations? – Andres H Nov 09 '20 at 04:17
  • `aggregate(cbind(time, weight)~id+type, bd, sum)` – Ronak Shah Nov 09 '20 at 04:18
  • @RonakShah can we do this dplyr way? – Ramakrishna S Nov 09 '20 at 08:49

0 Answers0