how to avoid this loop in R (rapply ? lapply ?) -
i'm trying replace loop symple command without succes (lapply ? rapply ? mapply ?). maybe it's rare case in r loops needed ?
n <- 10 x <- vector(mode="numeric", length=n) for(i in 2:n) { x[i] <- x[i-1]+runif(1) }
my question badly formulated. responses helped me understand need access values of vector function. loop simple function "f" can calculated:
x <- c(1,2,3,4) for(i in 2:4) { x[i] <- f(x[i-1]) }
maybe way global variables ?
for exact question, don't need apply
function @ all, because can vectorise cumsum
:
your code:
n <- 10 x <- vector(mode="numeric", length=n) set.seed(1) for(i in 2:n) { x[i] <- x[i-1]+runif(1) } x [1] 0.0000000 0.2655087 0.6376326 1.2104859 2.1186937 2.3203756 3.2187653 4.1634406 4.8242384 [10] 5.4533524
my code:
set.seed(1) c(0, cumsum(runif(n-1))) [1] 0.0000000 0.2655087 0.6376326 1.2104859 2.1186937 2.3203756 3.2187653 4.1634406 4.8242384 [10] 5.4533524
Comments
Post a Comment