简体   繁体   中英

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 <- 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. Any suggestions appreciated!

sweep() is a versatile little function that you can use here to divide each column by its own sum:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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