Re: [R] Scope and sapply

From: Worik R <worikr_at_gmail.com>
Date: Sun, 13 Jun 2010 15:40:34 +1200

I was careless.

Here is a better example of what I am trying to. With the '<<-' you offered.

?<<-

That was exactly what I needed, thankyou.

cheers
Worik

N <- 10
## x simulate a return series

x <- runif(N)-.5

## Build an array of cumulative returns of a portfolio starting with $1 as
it changes over time
y <- rep(0, length(x))
y[1] <- 1+1*x[1]
for(i in 2:N){
  y[i] <- y[i-1]+y[i-1]*x[i]
}

## y is that return series. Use

test.1 <- function(r.in){
  v <- rep(0, length(r.in))
  foo <- function(i, r){
    if(i == 1){
      s <- 1
    }else{
      s <<- v[i-1]
    }
    v[i] <<- s + s*r[i]
    return(v[i])
  }
  return(sapply(1:length(r.in), foo, r.in)) }

z <- test.1(x)
y
z

        [[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. Received on Sun 13 Jun 2010 - 05:27:53 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 Sun 13 Jun 2010 - 12:00:28 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