U-turn function in R?

R has a fold Reduce function. is there a corresponding reversal function? let's say given the initial value and recursively apply the function to get the array? The for loop will do the job, just wondering if there are more R-like ways to do this. thanks,

For example, the code below depicts a lorenz attractor in 8 lines (mimic F # Lorenz Attractor in 35 lines . But the for loop looks ugly. Can we do better?

 s <- 10; b <- 8/3; p <- 28 dt <- 0.003; n<-2000 x <- matrix(0,n,3); x[1,] <- c(10,0,20) for (i in 2:n){ x[i,] <- x[i-1,] + c(s * (x[i-1,2] - x[i-1,1]),x[i-1,1] * (p - x[i-1,3]) - x[i-1,2],x[i-1,1] * x[i-1,2] - b * x[i-1,3]) * dt } library(rgl) plot3d(x,type= 'l',col = 'red') 
+4
source share
1 answer

What about

 n<-2000 params <- list(s=10,b=8/3,p=28,dt=0.003) X0 <- X <- c(x=10,y=0,z=20) itfun <- function(X) { with(c(as.list(X),params), X + c(s*(yx),x*(pz)-y,x*yb*z)*dt) } Xmat <- rbind(X0,t(replicate(n,X <<- itfun(X)))) library(rgl) plot3d(Xmat,type= 'l',col = 'red') 

or (including response from comments)

 do.call(rbind, Reduce(function(X, i) { with(c(params, as.list(X)), X + c(s*(yx),x*(pz)-y,x*yb*z)*dt) }, seq(n), X, accumulate=TRUE)[-1]) 

PS How do you calculate the lines? If you use a sufficient number of semicolons, you can do it all on one line :-) I count 11 statements in your code

edit : some brackets were missing in update x

+2
source

Source: https://habr.com/ru/post/1332125/


All Articles