Hi TLowe, I'm not quite sure if I understand what you are trying to do. If you are trying to get the cumulative sum of your data frame along each column you can simply do
rcumsum=function(x){cumsum(x)/sum(x)} apply(tdat,2,rcumsum) Yet that is not what your code is doing. With a bit of clarification I may help you some more. Julian TLowe wrote: > Hey Folks, > > Could somebody help me rewrite the following code? > > I am looping through all records across 5 fields to calculate the cumulative > percentage of each record (relative to each individual field). > > Is there a way to rewrite it so I don't have to loop through each individual > record? > > ##### tdat is my data frame > ##### j is my field index > ##### k is my record index > ##### tsum is the sum of all values in field j > ##### tmp is a vector containing the values in field j > ##### tdat[k,paste("cpct,j,sep="")] creates new fields "cpct1",...,"cpct5" > > for(j in 1:5) { tsum<- sum(tdat[,j]); for(k in 1:nrow(tdat)) { td<- tdat[k,j]; tmp<-tdat[,j]; ##### sum values <= to current value and divide by the total sum tdat[k,paste("cpct",j,sep="")]<- sum(tmp[tmp <= td]) / tsum; } } > > > Thanks, > TLowe ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.