Converts a markovchain object to a plain, self-describing R list:
the same information toFile writes to disk, kept in memory.
fromDictionary reverses the conversion.
Usage
toDictionary(object)
# S4 method for class 'markovchain'
toDictionary(object)
fromDictionary(d)Arguments
- object
A
markovchainobject.- d
A list as returned by
toDictionary.d$transitionMatrixmay also be a plainn x nmatrix (with or without dimnames matchingd$states) for convenience when building a dictionary by hand rather than from an existingmarkovchainobject. When it is a plain matrix,d$byrowis honored exactly asnew("markovchain", ...)honors its ownbyrowargument: the matrix is stored as given, withd$byrowonly documenting whether it is row- or column-stochastic (so a column-stochastic matrix round-trips by settingd$byrow = FALSE, with no transposition performed here). Whend$transitionMatrixis a nested list (astoDictionaryproduces), the nesting itself is always keyed[[from]][[to]]– i.e. row-stochastic – so it is always reconstructed withbyrow = TRUE, regardless ofd$byrow.
Value
A named list with four elements:
nameThe chain's
name, as a single string (possibly empty).statesA character vector of state names, in order.
byrowAlways
TRUE: the list always stores the chain row-stochastically, regardless ofobject's own storage convention, so that the representation is unambiguous without also having to interpret this flag.transitionMatrixA named list of named lists:
transitionMatrix[[i]][[j]]is the probability of moving from stateito statej. This is deliberately not a plain matrix, so that the structure serializes to JSON or YAML (viatoFile) as a self-describing object keyed by state name, rather than a bare array whose meaning depends on remembering a row/column order.
fromDictionary returns a markovchain object.
Details
Unlike PyDTMC's own to_dictionary()/from_dictionary(),
which represent a chain as a flat mapping from every
(from_state, to_state) pair to its probability – \(n^2\)
entries with no state grouping – this nests the representation by
source state, which is both more compact to read and directly
round-trips through R's own list-of-lists idiom without any special
tuple-key handling.
Examples
statesNames <- c("a", "b")
mc <- new("markovchain", states = statesNames,
transitionMatrix = matrix(c(0.7, 0.3, 0.4, 0.6), byrow = TRUE,
nrow = 2, dimnames = list(statesNames, statesNames)))
d <- toDictionary(mc)
d$transitionMatrix$a$b # 0.3: probability of moving from "a" to "b"
#> [1] 0.3
identical(fromDictionary(d)@transitionMatrix, mc@transitionMatrix)
#> [1] TRUE