我的数据看起来像这样。
Weight Zip
23 88762
45.3 34957
37.6 87293
212.45 34957
58.3 87293
92.45 88762
我正在尝试对与相同邮政编码相对应的权重求和,并将结果添加到新列中:
TotalWeight
115.45
257.75
95.9
257.75
95.9
115.45
我想过做这样的事情,但我认为必须有更高效的东西。谢谢!
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)
}
答案 0 :(得分:2)
ave()
在这里工作:
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