R:使用转移矩阵的Montecarlo模拟

时间:2017-07-07 11:15:31

标签: r simulation montecarlo

我有一个转换矩阵:

if(!empty($content['body']){
print render($content['body']);
} else {
print render($content['field_image']);
}

我的数据集中有一个分类变量:

a
           A          B         C     D         E          F          G          H         I
A 0.00000000 0.66666667 0.0000000 0.000 0.0000000 0.00000000 0.00000000 0.33333333 0.0000000
B 0.08823529 0.02941176 0.2941176 0.000 0.2352941 0.05882353 0.02941176 0.11764706 0.1470588
C 0.00000000 0.37500000 0.0000000 0.000 0.4166667 0.00000000 0.00000000 0.08333333 0.1250000
D 0.00000000 0.00000000 0.3333333 0.000 0.0000000 0.00000000 0.33333333 0.33333333 0.0000000
E 0.00000000 0.50000000 0.2307692 0.000 0.0000000 0.00000000 0.00000000 0.07692308 0.1923077
F 0.00000000 0.00000000 0.0000000 0.000 0.5000000 0.00000000 0.00000000 0.00000000 0.5000000
G 0.00000000 0.50000000 0.0000000 0.500 0.0000000 0.00000000 0.00000000 0.00000000 0.0000000
H 0.00000000 0.27272727 0.3636364 0.000 0.1818182 0.00000000 0.00000000 0.00000000 0.1818182
I 0.00000000 0.31250000 0.1875000 0.125 0.3125000 0.00000000 0.00000000 0.06250000 0.0000000

现在我想使用我的转换矩阵来模拟变量,就像使用蒙特卡罗方法我的变量state=c("G" ,"I" ,"G", "C", "D", "I","A" ,"G", "G" ,"H", "C", "D" ,"C", "H" "F", "B", "F" ,"G" ,"D", "E" ,"B" ,"H" ,"E" ,"C" ,"F" ,"H", "C", "H" ,"F" ,"H") 一样。 你能告诉我哪个R包或功能可以帮我做模拟吗?

1 个答案:

答案 0 :(得分:1)

您可以使用包markovchainSequence中的markovchain。例如:

mat <- as.matrix(read.table(text="
0.00000000 0.66666667 0.0000000 0.000 0.0000000 0.00000000 0.00000000 0.33333333 0.0000000
0.08823529 0.02941176 0.2941176 0.000 0.2352941 0.05882353 0.02941176 0.11764706 0.1470588
0.00000000 0.37500000 0.0000000 0.000 0.4166667 0.00000000 0.00000000 0.08333333 0.1250000
0.00000000 0.00000000 0.3333333 0.000 0.0000000 0.00000000 0.33333333 0.33333333 0.0000000
0.00000000 0.50000000 0.2307692 0.000 0.0000000 0.00000000 0.00000000 0.07692308 0.1923077
0.00000000 0.00000000 0.0000000 0.000 0.5000000 0.00000000 0.00000000 0.00000000 0.5000000
0.00000000 0.50000000 0.0000000 0.500 0.0000000 0.00000000 0.00000000 0.00000000 0.0000000
0.00000000 0.27272727 0.3636364 0.000 0.1818182 0.00000000 0.00000000 0.00000000 0.1818182
0.00000000 0.31250000 0.1875000 0.125 0.3125000 0.00000000 0.00000000 0.06250000 0.000000",
           header=FALSE,stringsAsFactors = FALSE))
rownames(mat) <- colnames(mat) <- LETTERS[1:9]
mat[,9] <- 1-rowSums(mat[,1:8]) #To make sure your rows sum to 1

statesNames <- LETTERS[1:9]
markovchain_object <- new("markovchain", states = statesNames, transitionMatrix = mat)

markovchainSequence(n=10, markovchain = markovchain_object)

 [1] "C" "H" "C" "E" "C" "B" "C" "E" "B" "G"