Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions R/fittingFunctions.R
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,21 @@

markovchainSequence <-function (n, markovchain, t0 = sample(markovchain@states, 1),
include.t0 = FALSE, useRCpp = TRUE) {

# validate requested sequence length
if (!is.numeric(n) || length(n) != 1 || is.na(n) || !is.finite(n)) {
stop("`n` must be a finite numeric scalar")
}

if (!isTRUE(all.equal(n, round(n)))) {
stop("`n` must be an integer value")
}

n <- as.integer(n)

if (n < 0) {
stop("`n` must be greater than or equal to 0")
}

# check whether given initial state is possible state or not
if (!(t0 %in% markovchain@states))
Expand All @@ -42,17 +57,17 @@ markovchainSequence <-function (n, markovchain, t0 = sample(markovchain@states,
if (useRCpp) {
return(.markovchainSequenceRcpp(n, markovchain, t0, include.t0))
}

# R implementation of the function

# create a sequence of size n initially not initialized
chain <- rep(NA,n)
chain <- character(n)

# initial state
state <- t0

# populate the sequence
for (i in 1:n) {
for (i in seq_len(n)) {
# row probabilty corresponding to the current state
rowProbs <- markovchain@transitionMatrix[state, ]

Expand Down
12 changes: 12 additions & 0 deletions tests/testthat/testBasic1.R
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,18 @@ test_that("Output format of markovchainSequence", {
expect_equal(s6[1], "b")
})

test_that("markovchainSequence validates the requested length", {
expect_error(markovchainSequence(NA, mcB), "`n` must be a finite numeric scalar")
expect_error(markovchainSequence(1.5, mcB), "`n` must be an integer value")
expect_error(markovchainSequence(-1, mcB), "`n` must be greater than or equal to 0")
})

test_that("markovchainSequence returns zero-length sequences when requested", {
expect_equal(length(markovchainSequence(0, mcB)), 0)
expect_identical(markovchainSequence(0, mcB, include.t0 = TRUE, t0 = "b"), "b")
expect_identical(markovchainSequence(0, mcB, include.t0 = TRUE, t0 = "b", useRCpp = FALSE), "b")
})

statesNames <- c("a", "b", "c")
mcA <- new("markovchain", states = statesNames, transitionMatrix =
matrix(c(0.2, 0.5, 0.3, 0, 0.2, 0.8, 0.1, 0.8, 0.1), nrow = 3,
Expand Down
Loading