0

I am trying to avoid a loop in R. But I am having difficulties. At the moment this is the code that I have but I would really like to know if there is a direct way to do it (no loop). Triangle is just a IxJ matrix

I = 10
J = 10
xi <- rep(0,J) 
xi[1] <- 1
for(j  in 2:J){
  xi[j]<-(1/(I-j+1))*sum(log(Triangle[1:(I-j+1),j]/Triangle[1:(I-j+1),j-1]))
}
6
  • Could you tell more what you want to achieve with that code? Maybe desired output or equation? Commented Mar 17, 2014 at 11:28
  • 1
    I believe not, because your equation involves 1:(j+stuff) and you can't vectorize that. Commented Mar 17, 2014 at 11:30
  • I am trying to fill the vector xi with the formula, xi[j]<-(1/(I-j+1))*sum(log(Triangle[1:(I-j+1),j]/Triangle[1:(I-j+1),j-1])) But i was wondering if I could use some kind of ":" to avoid the loop here Commented Mar 17, 2014 at 11:45
  • Well, there's always the vectorize function. You'd have to run a time trial to see if it saves you anything in this simple case. Commented Mar 17, 2014 at 11:56
  • But how would I use the vectorize function here? Commented Mar 17, 2014 at 13:07

1 Answer 1

2

Here's a vectorized solution. However, this does not seem to improve efficiency.

mat <- matrix(NA, nrow=I, ncol=J)
smat1 <- cbind(FALSE, rbind(lower.tri(matrix(nrow=I-1, ncol=J-1), diag=TRUE)[(I-1):1,], FALSE))
smat2 <- lower.tri(matrix(nrow=I, ncol=J))[I:1,]
mat[smat1] <- Triangle[smat1] / Triangle[smat2]
res <- c(1, colMeans(log(mat), na.rm=TRUE)[-1])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.