我正在使用 R 編程語言。
我正在嘗試調整此處提供的答案(Manual simulation of Markov Chain in R)。下面的代碼根據一些用戶指定的概率模擬一些亂數:
alpha <- c(0,1,0,0, 0)
mat <- matrix(c(1,0,0,0,0,0.2,0.2,0.5,0.05,0.05, 0.3, 0.1,0.1,0.2,0.3, 0.2, 0.2, 0.2, 0.2, 0.2, 0,0,0,0,1), nrow = 5, ncol = 5, byrow = TRUE)
chainSim <- function(alpha, mat, n) {
out <- numeric(n)
out[1] <- sample(1:5, 1, prob = alpha)
for(i in 2:n)
out[i] <- sample(1:5, 1, prob = mat[out[i - 1], ])
out
}
當我們運行這個函式時,我們可以看到這些亂數的例子(這里,我們指定生成6個亂數的函式):
chainSim(alpha, mat, 6)
[1] 2 3 1 1 1 1
我想修改此代碼,以便在遇到第一個“1”或“5”時,序列停止。我嘗試按如下方式執行此操作(使用 WHILE 和 BREAK 命令):
alpha <- c(0,1,0,0, 0)
mat <- matrix(c(1,0,0,0,0,0.2,0.2,0.5,0.05,0.05, 0.3, 0.1,0.1,0.2,0.3, 0.2, 0.2, 0.2, 0.2, 0.2, 0,0,0,0,1), nrow = 5, ncol = 5, byrow = TRUE)
chainSim <- function(alpha, mat, n) {
out <- numeric(n)
out[1] <- sample(1:5, 1, prob = alpha)
for(i in 2:n) {
repeat{
out[i] <- sample(1:5, 1, prob = mat[out[i - 1], ])
out
if (1 %in% out[i] || 5 %in% out[i] ) break
}
}}
# simulate numbers until first 1 or 5 is encountered : does not work
chainSim(alpha, mat, n)
# repeat chainSim 100 times : does not work ("sim_final" will have likely have an uneven number of entries in each row)
sim <- replicate(chainSim(alpha, mat, n), n = 100)
sim_final = data.frame(t(sim))
但是當我嘗試這樣做時,chainSim() 不會產生任何亂數,而“sim”會產生 100 個 NULL。
有人可以告訴我如何解決這個問題嗎?
謝謝!
uj5u.com熱心網友回復:
不需要repeat
orwhile
回圈。下面的代碼在第一個 1 或 5 之后中斷。
要僅回傳該點之前的向量,請將函式的最后一條指令更改為out[out != 0]
. 但是回傳向量將具有不同的長度并且data.frame
沒有任何意義,replicate
應該保留一個串列的輸出。
chainSim <- function(alpha, mat, n) {
out <- integer(n)
out[1] <- sample(1:5, 1L, prob = alpha)
for(i in 2:n) {
if(out[i - 1L] %in% c(1, 5)) break
out[i] <- sample(1:5, 1L, prob = mat[out[i - 1], ])
}
out
}
alpha <- c(0, 1, 0, 0, 0)
mat <- matrix(c(1, 0, 0, 0, 0,
0.2, 0.2, 0.5, 0.05, 0.05,
0.3, 0.1, 0.1, 0.2, 0.3,
0.2, 0.2, 0.2, 0.2, 0.2,
0, 0, 0, 0, 1),
nrow = 5, ncol = 5, byrow = TRUE)
set.seed(2022)
n <- 6L
# simulate numbers until first 1 or 5 is encountered
chainSim(alpha, mat, n)
#> [1] 2 1 0 0 0 0
sim <- replicate(chainSim(alpha, mat, n), n = 100)
sim_final <- data.frame(t(sim))
head(sim_final)
#> X1 X2 X3 X4 X5 X6
#> 1 2 1 0 0 0 0
#> 2 2 1 0 0 0 0
#> 3 2 3 5 0 0 0
#> 4 2 3 1 0 0 0
#> 5 2 1 0 0 0 0
#> 6 2 3 4 4 4 1
由reprex 包于 2022-06-14 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/490977.html