简体   繁体   English

R过渡矩阵

[英]R Transition Matrix

I would like to convert a vector into a transitions matrix. 我想将向量转换为转换矩阵。 I have a vector t and divided this by its max value to get values between 0 and 1. I then made this into a matrix 我有一个向量t并将其除以最大值以得到0到1之间的值。然后将其制成矩阵

t <- c(22, 65, 37, 84, 36, 14, 9, 19, 5, 49)
x <- t/max(t)
y <- x%*%t(x)

My problem is that I want the columns of the matrix (y) to add up to 1, ie to make it into a transition matrix but I'm not sure how to do that. 我的问题是我希望矩阵(y)的列加起来为1,即使其成为过渡矩阵,但是我不确定该怎么做。 Any suggestions appreciated! 任何建议表示赞赏!

sweep() is a versatile little function that you can use here to divide each column by its own sum: sweep()是一个通用的小函数,您可以在这里使用它将每列除以自己的总和:

yy <- sweep(y, MARGIN = 2, STATS = colSums(y), FUN = "/")

## Confirm that the columns of yy all sum to 1
colSums(yy)
##  [1] 1 1 1 1 1 1 1 1 1 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM