Skip to content
Back to formatted view

Raw Message

Message-ID: <475D7EAF.4040602@u.washington.edu>
Date: 2007-12-10T18:00:15Z
From: Julian Burgos
Subject: Help rewriting looping structure?
In-Reply-To: <14196412.post@talk.nabble.com>

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