Re: [R] any alternatives for complex for-loops?

From: David Winsemius <dwinsemius_at_comcast.net>
Date: Wed, 12 Nov 2008 02:58:08 -0500

y <- rep(NA, length(x))
a <- 2:length(x)
y[a] <- complexFn( x[a-1], x[a] )

 > y
  [1] NA 1.5 2.5 3.5 4.5 5.5 6.5 7.5 8.5 9.5

-- 
David Winsemius

On Nov 12, 2008, at 12:48 AM, Kinoko wrote:


> Thanks for the replies
>
> Sorry for being unclear.
>
> I am asking if there is a way to process a vector in a way
> that uses references to other elements of the same vector.
> And doing this without a for-loop.
>
> Here is a running code:
>
> <code>
> complexFn <- function(a,b){
> c <- (a+b)/2
> return(c)
> }
>
> x <- 1:10
> y <- rep(NA, length(x))
>
> for (i in 1:length(x)){
> if(i>1){
> y[i] = complexFn(x[i-1], x[i])
> }
> }
> print(y)
> </code>
>
> And here is another attempt without the for-loop.
>
> <code>
> x <- 1:10
> x1 <- c(NA, x)
> length(x1)<-length(x)
>
> y<-mapply(complexFn,x,x1)
> print(c(y))
> </code>
>
> If someone could tell me the normal/elegant/effective/R way of
> doing this kind of vector processing, that would highly appreciated.
>
> best,
>
> gabor
>
> ______________________________________________
> 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 Wed 12 Nov 2008 - 08:01:26 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 Wed 12 Nov 2008 - 08:30:24 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.

list of date sections of archive