繁体   English   中英

查找与候选值向量中的值匹配的矩阵元素的数组索引

[英]Find array index of elements of a matrix that match a value in a vector of candidate values

我一直在googeling和stackoverflowing这一段时间,但我似乎无法找到正确的答案。

我有一个矩阵,包含不同的字符串,如"a""gamma" ,甚至包括强制字符的数字。

我如何获得的矩阵数组索引m若的元素m的candiate值的矢量值一致(注意,这些值可以是任意字符串)。 这是我试过的。 我虽然which(m %in% ...)会这样做,但它不会返回我的预期。

m <- matrix(c(0, "a", "gamma", 0, 0.5, 0, 0, 0, 0), ncol = 3)
m
#>      [,1]    [,2]  [,3]
#> [1,] "0"     "0"   "0" 
#> [2,] "a"     "0.5" "0" 
#> [3,] "gamma" "0"   "0"

which(m == "a", arr.ind = TRUE) # as expected
#>      row col
#> [1,]   2   1

which(m == "a" | m == "gamma", arr.ind = TRUE) # also obvious
#>      row col
#> [1,]   2   1
#> [2,]   3   1

candidates <- c("a", "gamma", "b")
which(m %in% candidates, arr.ind = TRUE) # not what I expected
#> [1] 2 3

reprex包创建于2019-09-11(v0.3.0)

  • 我想要的结果是m中元素的行和列索引与candiates中的值匹配。
  • 如果可能,我更喜欢基础R解决方案。

有帮助吗?

问题是%in%不保留输入的维度。 你可以编写自己的功能来做到这一点。 例如

`%matin%` <- function(x, table) {
  stopifnot(is.array(x))
  r <- x %in% table
  dim(r) <- dim(x)
  r
}

candidates <- c("a", "gamma", "b")
which(m %matin% candidates, arr.ind = TRUE)
#      row col
# [1,]   2   1
# [2,]   3   1

MrFlick的解决方案可能是你能得到的最好的解决方案之一,但如果你必须坚持基础R中的内置功能,这里有一种方法 -

which(matrix(m %in% candidates, dim(m)), arr.ind = T)

     row col
[1,]   2   1
[2,]   3   1

lapplyReduce另一种方式应该更快 -

which(Reduce("|", lapply(candidates, function(x) m == x)), arr.ind = T)

     row col
[1,]   2   1
[2,]   3   1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM