使用向量化或应用于从矩阵中提取值以绑定一个向量

时间:2018-09-21 14:46:08

标签: r

我有一个矩阵,在20个不同的位置包含20个项目,每个组合都有一个值。我想从此矩阵绘制许多不同的集合,而无需使用for循环并将所有内容绑定到向量。

set.seed(123)
mValues  <- matrix(runif(400, 5.0, 7.5), 20, 20)
mIndices <- matrix(c(sample(20),
                     sample(20),
                     sample(20),
                     sample(20),
                     sample(20)), 20, 5)

getValues <- function(mValues, mIndices, x){
  return(mValues[cbind(seq_along(mIndices[, x]),  mIndices[, x])])
}

反正有使用getValues函数并应用的方法吗?我想要的输出是:

c(getValues(mValues, mIndices, 1), 
  getValues(mValues, mIndices, 2),
  getValues(mValues, mIndices, 3),
  getValues(mValues, mIndices, 4),
  getValues(mValues, mIndices, 5))

2 个答案:

答案 0 :(得分:1)

您可以使用sapply(将返回一个矩阵)和as.vector

as.vector(sapply(1:5, function(x)
  getValues(mValues, mIndices, x = x)), mode = "double")
#  [1] 6.462250 6.036366 5.367621 5.662545 5.923722 6.202277 7.458375 6.485355
#  [9] 7.216173 6.830338 6.886188 5.632412 6.482614 5.410528 6.670712 7.249562
# [17] 7.455351 7.079819 5.771967 6.011276 5.596815 6.655794 5.931773 7.386185
# [25] 5.144896 6.203225 7.462392 5.087187 5.722899 6.230733 5.341350 5.857022
# ...

答案 1 :(得分:1)

我们可以遍历第三个参数

out <- c(sapply(1:5, getValues, mValues = mValues, mIndices = mIndices))
out
#[1] 6.462250 6.036366 5.367621 5.662545 5.923722 6.202277 7.458375 6.485355 7.216173 6.830338 6.886188
#[12] 5.632412 6.482614 5.410528 6.670712 7.249562 7.455351 7.079819 5.771967 6.011276 5.596815 6.655794
#[23] 5.931773 7.386185 5.144896 6.203225 7.462392 5.087187 5.722899 6.230733 5.341350 5.857022 6.997312
#[34] 6.842694 5.652142 5.550297 5.615219 6.324589 5.185961 5.544977 6.499972 7.402762 6.685467 5.922114
#[45] 6.216029 7.200616 5.162321 6.485355 7.216173 6.830338 7.442747 6.573053 6.482614 6.431584 5.886958
#[56] 7.409608 5.930595 6.603656 7.449555 6.432168 6.462250 5.884761 7.241847 5.922114 6.485858 6.087232
#[67] 7.025161 5.970798 5.050061 6.816756 7.392083 6.243818 6.355201 7.369317 5.119159 6.231416 7.455351
#[78] 5.594374 7.449555 5.579064 5.609049 5.023575 6.221533 6.715938 5.144896 6.771326 5.483447 5.552757
#[89] 5.573112 7.254686 6.205107 6.133335 6.775456 6.964220 6.327676 6.649596 7.429689 6.603656 6.111920
#[100] 5.936157

向量化方法是先复制行的序列,然后复制cbind,将'mIndices'作为vector,以提取'mValues'

out2 <- mValues[cbind(seq_len(nrow(mIndices)), c(mIndices))]
identical(out, out2)
#[1] TRUE