如何用值向量填充索引矩阵 [英] how to populate matrix of indices with vector of values

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

问题描述

我有一个矩阵(m.idx),其中包含我要索引的向量的位置元素.

I have a matrix (m.idx) containing position elements of a vector I want to index.

> m.idx
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    3    4    5    6    7
[3,]    5    6    7    8    9

假设x是我的向量.

x <- c(9,3,2,5,3,2,4,8,9)

我想用x的相应位置元素重新填充矩阵索引.

I want to repopulate the matrix index with the corresponding position elements of x.

所以我会有...

> m.pop
     [,1] [,2] [,3] [,4] [,5]
[1,]    9    3    2    5    3
[2,]    2    5    3    2    4
[3,]    3    2    4    8    9

我可以通过以下方式以一种笨拙的方式做到这一点.

I can kind of do it in a kludgy way with the following.

> m.pop <- t(matrix(t(matrix(x[c(t(m.idx))])),ncol(m.idx),nrow(m.idx)))

> m.pop
     [,1] [,2] [,3] [,4] [,5]
[1,]    9    3    2    5    3
[2,]    2    5    3    2    4
[3,]    3    2    4    8    9

但是似乎有一种更简单的方法来为值建立索引. 最好的方法(对于大型集合,最快/最有效)是什么?

But it seems like there may be an easier method to index the values. What is the best (and fastest/efficient for large sets) way to do this?

推荐答案

怎么样:

m.idx[] <- x[m.idx]
m.idx
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    9    3    2    5    3
# [2,]    2    5    3    2    4
# [3,]    3    2    4    8    9

或者,如果您不想覆盖m.idx矩阵,则可以执行以下操作:

Or if you don't want to overwrite the m.idx matrix, you can do this instead:

m.pop <- m.idx
m.pop[] <- x[m.pop]


已添加:

使用structure的另一种方法也非常快:

One other method, using structure, is also quite fast:

structure(x[m.idx], .Dim = dim(m.idx))
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    9    3    2    5    3
# [2,]    2    5    3    2    4
# [3,]    3    2    4    8    9

当应用于阿南达·马赫托答案中的大型m.idx矩阵时,我的机器上的计时是

When applied to the large m.idx matrix in Ananda Mahto's answer, the timings on my machine are

fun5 <- function() structure(x[m.idx], .Dim = dim(m.idx))
microbenchmark(fun1(), fun2(), fun3(), fun4(), fun5(), times = 10)
# Unit: milliseconds
#    expr       min        lq    median        uq       max neval
#  fun1()  303.3473  307.2064  309.2275  352.5076  353.6911    10
#  fun2()  548.0928  555.3363  587.6144  593.4492  596.5611    10
#  fun3()  480.6181  487.5807  507.5960  529.9696  533.0403    10
#  fun4() 1222.6718 1231.3384 1259.8395 1269.6629 1292.2309    10
#  fun5()  401.8450  403.7216  432.7162  455.4638  487.1755    10
identical(fun1(), fun5())
# [1] TRUE

您可以看到structure实际上在速度方面还不错.

You can see that structure is actually not too bad in terms of speed.

这篇关于如何用值向量填充索引矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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