2013-06-05 81 views
0

我寫了下面的代碼,我需要重複這個100次,我知道我需要用戶另一個循環,但我不知道該怎麼做。下面是代碼:嵌套for循環在R

mean <- c(5,5,10,10,5,5,5) 
x <- NULL 
u <- NULL 
delta1 <- NULL 
w1 <- NULL 

for (i in 1:7) { 
x[i] <- rexp(1, rate = mean[i]) 
u[i] <- (1/1.2)*runif(1, min=0, max=1) 
y1 <- min(x,u) 


if (y1 == min(x)) { 
delta1 <- 1 
} 
else { 
delta1 <- 0 
} 

if (delta1 == 0) 
{ 
w1 <- NULL 
} 

else { 

if(y1== x[[1]]) 
{ 
w1 <- "x1" 
} 
} 

} 
output <- cbind(delta1,w1) 
output 

我想要的最終輸出爲100行×3列的矩陣表示的運行數,DELTA1,和W1。

任何想法都將得到真正的讚賞。

+0

我不是確定這段代碼在做什麼。您正在以指數和均勻分佈進行繪製。然後你就可以從兩者中獲得最小化的實現。如果滾動最小值來自指數或不是,那麼您正在記錄。然後你測試'delta1 == 0'。我不知道你在這之後想要達到什麼目的。 – user1609452

+0

min(exp,unif)...如果min是exp,那麼delta1 = 1,如果min = unif,那麼delta1 = 0 ...現在在這個點之後...如果delta1 = 0,那麼w1 = NULL,如果min = exp(即x [[1]])生成的第一個值,那麼w1 =「x1」...等 – user9292

+0

是否要記錄從指數這是滾動最小值? – user1609452

回答

2

下面是我收集你想從你的代碼來實現:

  1. 鑑於從不同的分佈(指數分佈和均勻)繪製兩個向量
  2. 找出最小的數字來自哪個分佈從
  3. 重複這100次。

即使世界一對夫婦與您的代碼的問題,如果你想實現這一點,所以這裏的清理例如:

rates <- c(5, 5, 10, 10, 5, 5, 5) # 'mean' is an inbuilt function 
# Initialise the output data frame: 
output <- data.frame(number=rep(0, 100), delta1=rep(1, 100), w1=rep("x1", 100)) 
for (i in 1:100) { 
    # Generating u doesn't require a for loop. Additionally, can bring in 
    # the (1/1.2) out the front. 
    u <- runif(7, min=0, max=5/6) 
    # Generating x doesn't need a loop either. It's better to use apply functions 
    # when you can! 
    x <- sapply(rates, function(x) { rexp(1, rate=x) }) 
    y1 <- min(x, u) 

    # Now we can store the output 
    output[i, "number"] <- y1 
    # Two things here: 
    # 1) use all.equal instead of == to compare floating point numbers 
    # 2) We initialised the data frame to assume they always came from x. 
    #  So we only need to overwrite it where it comes from u. 
    if (isTRUE(all.equal(y1, min(u)))) { 
     output[i, "delta1"] <- 0 
     output[i, "w1"] <- NA # Can't use NULL in a character vector. 
    } 
} 
output 
+0

非常感謝!最終,我想說如果min = x [[i]],那麼w1 =「xi」,i = 1,... 10。難以更改代碼嗎?再次感謝! – user9292

+0

試一試。您可以添加一個else語句,然後使用'which()'獲取最小值的索引,然後使用'paste0'將索引與索引連接起來 –

1

下面是與replicate替代,更有效的方法:

Mean <- c(5, 5, 10, 10, 5, 5, 5) 

n <- 100 # number of runs 

res <- t(replicate(n, { 
      x <- rexp(n = length(Mean), rate = Mean) 
      u <- runif(n = length(Mean), min = 0, max = 1/1.2) 
      mx <- min(x) 
      delta1 <- mx <= min(u) 
      w1 <- delta1 & mx == x[1] 
      c(delta1, w1) 
      })) 

output <- data.frame(run = seq.int(n), delta1 = as.integer(res[ , 1]), 
        w1 = c(NA, "x1")[res[ , 2] + 1]) 

結果:

head(output) 

#  run delta1 w1 
# 1 1  1 <NA> 
# 2 2  1 <NA> 
# 3 3  1 <NA> 
# 4 4  1 x1 
# 5 5  1 <NA> 
# 6 6  0 <NA>