【发布时间】:2020-01-13 11:00:46
【问题描述】:
我已经在谷歌上搜索和堆栈溢出了一段时间,但我似乎找不到正确的答案。
我有一个矩阵,其中包含不同的字符串,例如"a"、"gamma",甚至是强制转换为字符的数字。
如果m 的元素与候选值向量中的值匹配,我如何获取矩阵m 的数组索引(请注意,这些值可以是任何字符串)。这是我尝试过的。我虽然 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 package (v0.3.0) 于 2019 年 9 月 11 日创建
- 我想要的结果是
m中元素的行列索引 匹配candiates中的值。 - 如果可能,我更喜欢基础 R 解决方案。
有什么帮助吗?
【问题讨论】: