I am building a transition matrix for some markov chains, so I need all rows to add up to 1.
I create a random ten-state 10 x 10 matrix with:
new_vector <- runif(10^2,0,1)
new_matrix <- matrix(new_vector,
ncol=10,
nrow=10,
byrow=TRUE,
dimnames=list(from_state=sprintf("State_No.%s", rep(1:10)),
to_state=sprintf("State_No.%s", rep(1:10)))
But when I use apply() , {x/sum(x)} it still sums by columns and not by rows even if I've indicated margin=1.
I've succeeded by transposing and retransposing the matrix back again as below, but is there a quicker way? I have tried Rowsum and Rowsums but the error that this flags is that these functions operate on more than one dimension like an array, so not 1 line of x in a matrix.
transition_matrix <- new_matrix %>%
t() %>%
apply(1, function(x) {x/sum(x)}) %>%
t()
Any of the codes below will work
prop.table(new_matrix, 1)
proportions(new_matrix, 1)
new_matrix / rowSums(new_matrix)
sweep(new_matrix, 1, rowSums(new_matrix), '/')
t(apply(new_matrix, 1, function(x)x/sum(x)))