简体   繁体   中英

R - Looping within a loop

I have used the following code to calculate the log-likelihood of a function where the x parameters (x1, x2, x3, x4, x5) are uniformly distributed random numbers between 0 and 1, but the function is also dependent on the values of t (which is a vector).

library(expm)
t <- seq(10,1000,by=5)

x1 <- runif(1,0,1)
x2 <- runif(1,0,1)
x3 <- runif(1,0,1)
x4 <- runif(1,0,1)
x5 <- runif(1,0,1)

p <- matrix(c(1,0,0), nrow=1, ncol=3, byrow=TRUE)

q <- matrix(c(x1,x2,x3), nrow=3, ncol=1, byrow=TRUE)

likely <- vector()

for (i in 1:length(t)) {
likely[i] <- p%*%expm(matrix(c(-(x4+x1)*t[i],x4*t[i],0,0,-(x5+x2)*t[i],x5*t[i],0,0,-x3*t[i]), nrow=3, ncol=3, byrow=TRUE))%*%q
}

log.likely <- vector()

for (i in 1:length(t)) {
log.likely[i] <- log(likely[i])
}

L3 <- -(sum(log.likely))
L3

My question is: how do I run this code say, 100 times, for different values of the x parameters? I already have a loop within the code to run through the different values of t. But now I need to loop over different values of x1, x2, x3, x4, and x5. Any help would be greatly appreciated!

I'm not sure if this is exactly what you're going for or not, but this will allow you to run your code however many times you want to, and store the results in a list containing all of the x values and the log likelyhood for the values.

log.likelyhood <- function(){
  require(expm)

  t <- seq(10,1000,by=5)

  x1 <- runif(1,0,1)
  x2 <- runif(1,0,1)
  x3 <- runif(1,0,1)
  x4 <- runif(1,0,1)
  x5 <- runif(1,0,1)

  p <- matrix(c(1,0,0), nrow=1, ncol=3, byrow=TRUE)

  q <- matrix(c(x1,x2,x3), nrow=3, ncol=1, byrow=TRUE)

  likely <- vector()

  for (i in 1:length(t)) {
    likely[i] <- p%*%expm(matrix(c(-(x4+x1)*t[i],x4*t[i],0,0,-(x5+x2)*t[i],x5*t[i],0,0,-x3*t[i]), nrow=3, ncol=3, byrow=TRUE))%*%q
  }

  log.likely <- vector()

  for (i in 1:length(t)) {
    log.likely[i] <- log(likely[i])
  }

  L3 <- -(sum(log.likely))

  return(list(xvals = c(x1, x2, x3, x4, x5), L3 = L3))
}

results <- replicate(100, log.likelyhood(), simplify = FALSE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM