在二进制矩阵中提取值为1的列名 [英] Extract column names with value 1 in binary matrix

查看:91
本文介绍了在二进制矩阵中提取值为1的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题;我想从一个像这样的二进制矩阵开始创建一个新矩阵:

I have a problem; i would like to create a new matrix starting from a binary matrix structured like this:

  A B C D E F
G 0 0 1 1 0 0
H 0 0 0 1 1 0
I 0 0 0 0 1 0
L 1 1 0 0 0 0

我想创建一个由起始行的行名称和一个名为X的新的唯一列组成的新矩阵,该列中的每一行都包含每个列的名称对应的矩阵号为1的时间.

i want to create a new matrix made by row names of the starting one, and a new and unique column, called X, which contains for every rows, the name/names of the column every time the correspondent matrix number is 1.

我该怎么办?

推荐答案

m是您的矩阵的情况下尝试以下操作:

Try this where m is your matrix:

as.matrix(apply(m==1,1,function(a) paste0(colnames(m)[a], collapse = "")))

#  [,1]
#G "CD"
#H "DE"
#I "E" 
#L "AB"

如果m较大,则可能更快的另一种选择:

Another option which might be faster if m is large:

t <- which(m==1, arr.ind = TRUE)
as.matrix(aggregate(col~row, cbind(row=rownames(t), col=t[,2]), function(x) 
                                                    paste0(colnames(m)[x], collapse = "")))

这篇关于在二进制矩阵中提取值为1的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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