n<-1000 Id<-sort(sample(1:50,size=n,rep=T)) table(Id) X<-rnorm(n) CX<-unlist(tapply(X,Id,cumsum)) Xdf<-data.frame(Id,X,CX) Xdf[1:40,] Xm<-matrix(rep(1:10,each=2),ncol=2,byrow=T) xv<-1:10 apply(Xm,2,function(x){mapply(xv,x,FUN="*")})