过渡矩阵

May*_*you 5 r matrix

考虑以下数据帧:

 df = data.frame(cusip = paste("A", 1:10, sep = ""), xt = c(1,2,3,2,3,5,2,4,5,1), xt1 = c(1,4,2,1,1,4,2,2,2,5))
Run Code Online (Sandbox Code Playgroud)

数据分为五种状态,即现实中的分位数:1,2,3,4,5.数据帧的第一列表示时间t的状态,第二列是时间t + 1的状态.

我想计算一种五种状态的转换矩阵.矩阵的含义如下:

  • (Row,Col)=(1,1):在时间t处于分位数1中的cusips的百分比,并且在时间t + 1中保持为1
  • (Row,Col)=(1,2):在t处的分位数1中的cusips的百分比,并且在t + 1处变为分位数2
  • 等等...

我真的不确定如何以有效的方式做到这一点.我觉得答案是微不足道的,但我无法理解它.

有人可以帮忙吗?

Jos*_*ien 5

res <- with(df, table(xt, xt1)) ## table() to form transition matrix
res/rowSums(res)                ## /rowSums() to normalize by row
#    xt1
# xt          1         2         4         5
#   1 0.5000000 0.0000000 0.0000000 0.5000000
#   2 0.3333333 0.3333333 0.3333333 0.0000000
#   3 0.5000000 0.5000000 0.0000000 0.0000000
#   4 0.0000000 1.0000000 0.0000000 0.0000000
#   5 0.0000000 0.5000000 0.5000000 0.0000000

## As an alternative to  2nd line above, use sweep(), which won't rely on 
## implicit recycling of vector returned by rowSums(res)
sweep(res, MARGIN = 1, STATS = rowSums(res), FUN = `/`)
Run Code Online (Sandbox Code Playgroud)