1
library(markovchain)

P <- matrix(c(0, 0.5, 0.5, 0, 0, 0,
          1, 0, 0, 0, 0, 0,
          1, 0, 0, 0, 0, 0,
          0, 0, 0, 0.25, 0.5, 0.25,
          0, 0, 0, 0.5, 0.25, 0.25,
          0, 0, 0, 0, 0, 1), nrow = 6, ncol = 6, byrow = TRUE)

mc <- new("markovchain", states = 1:6, transitionMatrix = P, name = "X")

periods <- period(mc)

cat("Periodicity of the states:\n")
print(periods)

Here I wrote this code to find out the period of each state. But got this error: "

Error in validObject(.Object) : invalid class “markovchain” object: invalid object for slot "states" in class "markovchain": got class "integer", should be or extend class "character"

To solve this error, I wrote this code:

# Load the markovchain package
library(markovchain)

# Define the transition matrix
P <- matrix(c(0, 0.5, 0.5, 0, 0, 0,
          1, 0, 0, 0, 0, 0,
          1, 0, 0, 0, 0, 0,
          0, 0, 0, 0.25, 0.5, 0.25,
          0, 0, 0, 0.5, 0.25, 0.25,
          0, 0, 0, 0, 0, 1), nrow = 6, ncol = 6, byrow = TRUE)

# Create a markovchain object
states <- as.character(1:6)
mcP <- new("markovchain", states = states, transitionMatrix = P, name = "X")

# Compute the periodicity of the states
periods <- period(mc)

# Print the periodicity of the states
cat("Periodicity of the states:\n")
print(periods)

Then I got this warning:

Warning: The matrix is not irreduciblePeriodicity of the states: [1] 0

here I also got periodicity 0

But when I calculated in hand I found the Period of each state: 1 2 2 1 1 1 respectively.

How can I get this result in code also?

M--
  • 25,431
  • 8
  • 61
  • 93

1 Answers1

1

from the documentation of ?markovchain::period:

period returns a integer number corresponding to the periodicity of the Markov chain (if it is irreducible)

your example chain is not irreducible (e. g. from state 1 you can only ever reach states 2 and 3 and back to 1 again):

> is.irreducible(mc)
[1] FALSE
I_O
  • 4,983
  • 2
  • 2
  • 15