过渡矩阵力ncol等于nrows [英] transition matrix force ncol to equal nrows

查看:116
本文介绍了过渡矩阵力ncol等于nrows的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个转换矩阵,作为从簇"(行)到簇"(列)的频率.想想马尔可夫链.

I have created a transition matrix as a 'from cluster' (rows) 'to cluster' (columns) frequency. Think Markov chain.

假设我有5个群集,但只有3个群集,那么我得到一个5 * 3的转换矩阵.如何使其成为5 * 5转换矩阵?有效地显示所有零列吗?

Assume I have 5 from clusters but only 3 to clusters then I get a 5*3 transition matrix. How do a force it to be a 5*5 transition matrix? Effectively how to I show the all zero columns?

我正在寻求一种优雅的解决方案,因为它将应用于涉及数百个集群的更大问题.我真的很不熟悉R Matrix,据我所知,我不知道一种强制列数输入行数然后归零的优雅方法,除了使用for循环外,其他任何方法都不为零,这是我的直觉.最佳解决方案.

I'm after an elegant solution as this will be applied on a much larger problem involving hundreds of clusters. I am really quite unfamiliar with R Matrix's and to my knowledge I don't know of an elegant way to force number of columns to enter number of rows then impute zero's where no match except for using a for loop which my hunch is that's not the best solution.

示例代码:

# example data
cluster_before <- c(1,2,3,4,5)
cluster_after <- c(1,2,4,4,1)

# Table output
table(cluster_before,cluster_after)
# ncol does not = nrows. I want to rectify that

# I want output to look like this:
what_I_want <- matrix(
  c(1,0,0,0,0,
    0,1,0,0,0,
    0,0,0,1,0,
    0,0,0,1,0,
    1,0,0,0,0),
  byrow=TRUE,ncol=5
)

# Possible solution. But for loop can't be best solution?
empty_mat <- matrix(0,ncol=5,nrow=5)

matrix_to_update <- empty_mat

for (i in 1:length(cluster_before)) {
val_before <- cluster_before[i]
val_after <- cluster_after[i]
matrix_to_update[val_before,val_after] <- matrix_to_update[val_before,val_after]+1
}
matrix_to_update
# What's the more elegant solution?

在此先感谢您的帮助.非常感谢.

Thanks in advance for your help. It's much appreciated.

推荐答案

将它们设置为factor s,然后将其设置为table:

Make them factors and then table:

levs <- union(cluster_before, cluster_after)
table(factor(cluster_before,levs), factor(cluster_after,levs))

#    1 2 3 4 5
#  1 1 0 0 0 0
#  2 0 1 0 0 0
#  3 0 0 0 1 0
#  4 0 0 0 1 0
#  5 1 0 0 0 0

这篇关于过渡矩阵力ncol等于nrows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆