Generate a Markov chain for n individuals or units by specifying a transition matrix.

addMarkov(
  dd,
  transMat,
  chainLen,
  wide = FALSE,
  id = "id",
  pername = "period",
  varname = "state",
  widePrefix = "S",
  start0lab = NULL,
  trimvalue = NULL
)

Arguments

dd

data.table with a unique identifier

transMat

Square transition matrix where the sum of each row must equal 1. The dimensions of the matrix equal the number of possible states.

chainLen

Length of each chain that will be generated for each chain; minimum chain length is 2.

wide

Logical variable (TRUE or FALSE) indicating whether the resulting data table should be returned in wide or long format. The wide format includes all elements of a chain on a single row; the long format includes each element of a chain in its own row. The default is wide = FALSE, so the long format is returned by default.

id

Character string that represents name of "id" field. Defaults to "id".

pername

Character string that represents the variable name of the chain sequence in the long format. Defaults "period",

varname

Character string that represents the variable name of the state in the long format. Defaults to "state".

widePrefix

Character string that represents the variable name prefix for the state fields in the wide format. Defaults to "S".

start0lab

Character string that represents name of the integer field containing starting state (State 0) of the chain for each individual. If it is NULL, starting state defaults to 1. Default is NULL.

trimvalue

Integer value indicating end state. If trimvalue is not NULL, all records after the first instance of state = trimvalue will be deleted.

Value

A data table with n rows if in wide format, or n by chainLen rows if in long format.

Examples

def1 <- defData(varname = "x1", formula = 0, variance = 1)
def1 <- defData(def1, varname = "x2", formula = 0, variance = 1)
def1 <- defData(def1,
  varname = "S0", formula = ".6;.3;.1",
  dist = "categorical"
)

dd <- genData(20, def1)

# Transition matrix P

P <- t(matrix(c(
  0.7, 0.2, 0.1,
  0.5, 0.3, 0.2,
  0.0, 0.7, 0.3
),
nrow = 3
))

d1 <- addMarkov(dd, P, chainLen = 3)
d2 <- addMarkov(dd, P, chainLen = 5, wide = TRUE)
d3 <- addMarkov(dd, P, chainLen = 5, wide = TRUE, start0lab = "S0")
d4 <- addMarkov(dd, P, chainLen = 5, start0lab = "S0", trimvalue = 3)