Re: [R] Help rewriting looping structure?

From: Law, Jason <jason.law_at_bes.ci.portland.or.us>
Date: Thu, 6 Dec 2007 11:03:31 -0800


This will give you the percents in the same order as your original data (as this is what your original code did)

apply(tdat, 2,
function(x) {

	o <- order(x)
	oldo <- order(o)
	prc <- cumsum(x[o]) / sum(x)
	prc[oldo]

})

Jason Law
Statistician
City of Portland, Bureau of Environmental Services Water Pollution Control Laboratory
6543 N Burlington Avenue
Portland, OR 97203 -5452
jlaw_at_bes.ci.portland.or.us

-----Original Message-----
From: r-help-bounces_at_r-project.org
[mailto:r-help-bounces_at_r-project.org]On Behalf Of TLowe Sent: Thursday, December 06, 2007 10:28 AM To: r-help_at_r-project.org
Subject: Re: [R] Help rewriting looping structure?

Thank you all. That's exactly what I was looking for.

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
>

-- 
View this message in context:
http://www.nabble.com/Help-rewriting-looping-structure--tf4957267.html#a1419
8294
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-help_at_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.

______________________________________________
R-help_at_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.
Received on Thu 06 Dec 2007 - 19:02:23 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 06 Dec 2007 - 19:30:18 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.