user3483060
user3483060

Reputation: 407

Create a frequency table by cross table

I am using the library msm in R

I would like to create the output of this function (statetable.msm) by my own.

I would like to understand how to create the table obtained by:

statetable.msm(state = state, subject = PTNUM, data = cav)

How to create by hand this table?

I was trying something like this without success.

table(cav$state,cav$state)

I am creating this code but it does not works I dont understand why:

    library(msm)
    lista<-list()
    AA<-unique(cav$PTNUM)  ## Create the unique ids of patients
    for(i in AA){   # I loop over the patients and filter the main 
       dataset
    lista[[i]]<-cav|>
mutate(o_state=state)|> # Here I create a new o_state to create the 
  #cartesian product
filter(PTNUM==AA[i])|># Here I filter the dataset to analyze each 
  patient
select(state,o_state)|># From here I do the cartesian product
table()|>
data.frame()
    }

Upvotes: 0

Views: 37

Answers (1)

CPB
CPB

Reputation: 756

You can inspect the function code by running the function name (without brackets or arguments). The key is working out the previous state and previous subject to construct the transition matrix, in this case by taking the lagged variable. I have also added an alternative construction using data.table.

library(msm)

# Start by looking at the function code
statetable.msm

statetable.msm <- function(state, subject, data = NULL){
  if (!is.null(data)) {
    data <- as.data.frame(data)
    state <- eval(substitute(state), data, parent.frame())
  }
  n <- length(state)
  if (!is.null(data)) 
    subject <- if (missing(subject)) 
      rep(1, n)
  else eval(substitute(subject), data, parent.frame())
  subject <- match(subject, unique(subject))
  prevsubj <- c(NA, subject[1:(n - 1)])
  previous <- c(NA, state[1:(n - 1)])
  previous[prevsubj != subject] <- NA
  ntrans <- table(previous, state)
  names(dimnames(ntrans)) <- c("from", "to")
  ntrans
}

# An alternative calculation in data.table
cav_dt <- as.data.table(cav)
cav_dt[, prev_state := shift(state), by = PTNUM]
cav_dt[, prev_subject := shift(PTNUM)]

cav_dt[!is.na(prev_state), .(count = .N), 
       keyby = .(prev_state, state)] %>%
  dcast(prev_state ~ state, value.var = 'count')

Upvotes: 0

Related Questions