Optimising nested for loops in R

Viewed 85

I tried to speed the below code but without any success.

I read about Rfast package but I also fail in implementing that package.

Is there any way to optimise the following code in R?

RI<-function(y,x,a,mu,R=500,t=500){
  x <- as.matrix(x)
  dm <- dim(x)
  n <- dm[1]  
  bias1 <- bias2 <- bias3 <- numeric(t)
  b1 <- b2<- b3 <- numeric(R) 
  ### Outliers in Y ######
  for (j in 1:t) {
  for (i in 1:R) {
    id <- sample(n, a * n)
    z <- y
    z[id] <- rnorm(id, mu) 
    b1[i] <- var(coef(lm(z ~., data = as.data.frame(x))))
    b2[i] <- var(coef(rlm(z ~ ., data = data.frame(x), maxit = 2000, method = "MM")))
    b3[i] <- var(coef(rlm(z ~ ., data = data.frame(x), psi = psi.huber,maxit = 300)))
  }
      bias1[j] <- sum(b1)    ;   bias2[j] <- sum(b2);   bias3[j] <- sum(b3)
  }
  bias <- cbind("lm" = bias1,"MM-rlm" = bias2, "H-rlm" = bias3)
  colMeans(bias)
  }
#######################################
p <- 5
n <- 200
x<- matrix(rnorm(n * p), ncol = p)
y<-rnorm(n)
a=0.2
mu <-10
#######################################
RI(y,x,a,mu)
0 Answers
Related