R:矩阵到索引 [英] R: matrix to indexes

查看:92
本文介绍了R:矩阵到索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似

      [,1] [,2]
 [1,]    1    3
 [2,]    4    6
 [3,]   11   12
 [4,]   13   14

我想将此矩阵转换为这样的向量:

I want to convert this matrix to a vector like this:

# indices 1-6, 11-14 = 1, gap indices 7-10 = 0
xx <- c(1,1,1,1,1,1,0,0,0,0,1,1,1,1)

这个想法:矩阵的值从1到14.向量的长度也为14.如果您假设第一列为 start ,第二列为 end ,然后针对矩阵中存在的那些 range ,即1-3、4-6、11-12、13-4(或等效地1-6、11- 14),我希望这些索引处的值在我的输出向量中为1.我的矩阵中 gap 的值为7-10,在我的输出矢量的索引7-10处的值为0. (感谢您的修改)

The idea: The matrix has values from 1 through 14. And the length of the vector is also 14. If you assume the first column to be the start and the second column to be the end, then for those ranges present in the matrix, i.e., 1-3, 4-6, 11-12, 13-4 (or equivalently 1-6, 11-14), I want the values at these indices to be 1 in my output vector. And the gap of 7-10 in my matrix should have a value of 0 at indices 7-10 in my output vector. (Thanks for the edit)

但是,有时矩阵不给出矩阵中的最后一个值.但是,我一直都知道变换后的大小,在这种情况下,假设为20.然后,生成的向量应如下所示:

However, sometimes the matrix does not give the last value in the matrix. However, I always know the size of after the transformation, let say, in this case, 20. Then, the resulting vector should like this:

# indices 1-6, 11-14 = 1, gap indices 7-10 = 0, indices 15-20 = 0
xx <- c(1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,0,0)

我该怎么做而不循环?我的矩阵很长,我尝试使用循环速度很慢.

How can I do that without a loop? My matrix is quite long, I tried using loop is slow.

推荐答案

以下是使用IRanges软件包的答案:

Here's an answer using IRanges package:

require(IRanges)
xx.ir <- IRanges(start = xx[,1], end = xx[,2])
as.vector(coverage(xx.ir))
# [1] 1 1 1 1 1 1 0 0 0 0 1 1 1 1

如果您指定整个矢量长度的minmax值,则:

If you specify a min and max value of your entire vector length, then:

max.val <- 20
min.val <- 1
c(rep(0, min.val-1), as.vector(coverage(xx.ir)), rep(0, max.val-max(xx)))

这篇关于R:矩阵到索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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