我正在使用R编程语言。
我正试图适应这里提供的答案(手动模拟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
有人能告诉我如何解决这个问题吗?
谢谢!
不需要repeat
或while
环。下面的代码在第一个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包(v2.0.1)创建于2022-06-14