Fran
Fran

Reputation: 3

R: How could I change this loop to apply?

I'm currently working on an R program, where there is one part of this program that computes in a loop two values which are interdependant. Although since I have to do 100,000 iterations it takes so long time.

So I would like to substitute this for loop for an apply loop or some more efficient function, but I don't know how to do it. Could someone help me?

p <- c()
for(i in 1:n) {
  if(i == 1) {
   x <- b[i]
  }
  else {
    x <- c(x, max(h[i - 1], p[i]))
  }
  h <- c(h, x[i] + y[i])
}

Thank you very much!!

Upvotes: 0

Views: 68

Answers (1)

K. A. Buhr
K. A. Buhr

Reputation: 50864

You don't seem to have a full working example here, but the main problem is that building up the x and h vectors with the c() function is very slow. It's better to preallocate them:

x <- numeric(n)  # allocate vector of size n
h <- numeric(n)

and then fill them in as you go by assigning to x[i] and h[i]. For example, the following loop:

x <- c(); for (i in 1:100000) x <- c(x,1)

takes about 10 seconds to run on my laptop, but this version:

x <- numeric(100000); for (i in 1:100000) x[i] <- 1

does the same thing while running almost instantly.

Upvotes: 5

Related Questions