File: random.R

package info (click to toggle)
r-cran-markovchain 0.8.5-4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,060 kB
  • sloc: cpp: 2,854; sh: 13; makefile: 2
file content (49 lines) | stat: -rw-r--r-- 1,257 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# Methods to generate random markov chains

normalizeMatrix <- function(matrix, byrow = TRUE) {
  margin <- ifelse (byrow, 1, 2)
  n <- nrow(matrix)
  
  result <- sapply(1:n, function(i) {
    row <- matrix[i, ]
    rowSum <- sum(row)
    
    if (rowSum == 0) {
      values <- c(rep(0, i - 1), 1, rep(0, n - i))
      values
    } else {
      row / rowSum
    }
  })
  
  # If we want the result by rows, we have to transpose the matrix,
  # since the apply method with margin = 1 (over rows) returns the result
  # by columns
  if (byrow)
    t(result)
  else
    result
}


# Returns a random stochastic matrix
randomStochasticMatrix <- function(n, zeroProb, byrow = TRUE) {
  numRandom <- n * n
  randomNums <- stats::runif(numRandom)
  
  remainProb <- (1 - zeroProb) / numRandom
  probs <- c(zeroProb, rep(remainProb, numRandom))
  
  entries <- sample(c(0, randomNums), numRandom, prob = probs, replace = TRUE)
  
  result <- matrix(entries, n, n, byrow)
  result <- normalizeMatrix(result, byrow)
  
  result
}


randomMarkovChain <- function(n, zeroProb = 0.95, byrow = TRUE) {
  matrix <- randomStochasticMatrix(n, zeroProb, byrow)
  new("markovchain", transitionMatrix = matrix, byrow = byrow)
}