[R] Scope and sapply
Berend Hasselman
bhh at xs4all.nl
Sun Jun 13 11:44:50 CEST 2010
Worik R wrote:
>
> ...
>
> 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))
> }
>
How about
cumprod(1+x)
/Berend
--
View this message in context: http://r.789695.n4.nabble.com/Scope-and-sapply-tp2253158p2253313.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list