0

I have data that looks like this.

    Weight     Zip
    23         88762
    45.3       34957
    37.6       87293
    212.45     34957
    58.3       87293
    92.45      88762

I am trying to sum the weights that correspond to the same zip code and add the result to a new column:

    TotalWeight
    115.45
    257.75
    95.9
    257.75 
    95.9 
    115.45

I thought about doing something like this but I figure there must be something more efficient. Thanks!

weight <- c(23, 45.3, 37.6, 212.45, 58.3, 92.45)
zip <- c(88762L, 34957L, 87293L, 34957L, 87293L, 88762L)

function(){
zippop<-data.frame()
for (i in unique(zip)){
zippop<-rbind(zippop, c(i,sum(weight[which(zip==i)])))}
return (zippop)
}
AffableAmbler
  • 377
  • 3
  • 15
  • Please make your example reproducible. That is, rather than only showing your data, make the start of your code create it, e.g. like so: `weight <- c(23, 45.3, 37.6, 212.45, 58.3, 92.45)` and (assuming you want `zip` as integer) `zip <- c(88762L, 34957L, 87293L, 34957L, 87293L, 88762L)` – Glen_b Feb 27 '16 at 03:20
  • I took the liberty of adding those lines for you, but your function is not immediately executable as it stands either so you should still edit your code. – Glen_b Feb 27 '16 at 03:24

1 Answers1

2

ave() works here:

df <- data.frame(Weight=c(23,45.3,37.6,212.45,58.3,92.45),Zip=c(88762,34957,87293,34957,87293,88762));
df$TotalWeight <- ave(df$Weight,df$Zip,FUN=sum);
df;
##   Weight   Zip TotalWeight
## 1  23.00 88762      115.45
## 2  45.30 34957      257.75
## 3  37.60 87293       95.90
## 4 212.45 34957      257.75
## 5  58.30 87293       95.90
## 6  92.45 88762      115.45
bgoldst
  • 34,190
  • 6
  • 38
  • 64