[R] Fwd: for loop
Michael Bedward
michael.bedward at gmail.com
Tue Sep 21 09:40:22 CEST 2010
First up, you've got a problem if your vectors are 520 elements in
length because you accessing element i+1 in your loop and when i is
520 you won't have a valid value.
Next, you don't really need a for loop at all :) You can do those
operations on the whole vectors...
e.g. tmp1 <- (1 - samp.pct[-n)^2 * diff(log(1 - theor.pct))
(just replaced your explicit subtraction of lagged values with diff)
Does that help ?
Michael
Note, in the line above, the last element is omitted with "[-n]". See
help page on the diff function if you are not familiar with it.
On 21 September 2010 16:41, andre bedon <andresago1 at hotmail.com> wrote:
>
> Hi guys,
>
> Im new to R and am having a bit of trouble with what should be a simple loop. It sprobably something very fundamental that im doing wrong.
>
>
>
> for(i in c(1:520))
> {
> tmp1<- ((1-samp.pct[i])^2)*(log(1-theor.pct[i])-log(1-theor.pct[i+1]))
> tmp2<- ((samp.pct[i])^2)*(log(theor.pct[i+1])-log(theor.pct[i]))
> }
> ADtest.stat<- (-n*(max(theor.pct))) + (n*sum(tmp1)) + (n*sum(tmp2))
> names(ADtest.stat) <- c("Anderson-Darling test statistic")
> print(ADtest.stat)
>
>
>
> samp.pct is a vector containing 520 values between 0 and 1, so is theor.pct. n is 520.
>
> After running this code, tmp1 and tmp2 return only one value, where I need around 520 values. Any ideas would be appreciated.
>
>
>
> Regards,
>
>
>
> Andre
>
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>
More information about the R-help
mailing list