我有一个索引矩阵,该索引引用带有名称的向量。 (作为最近邻居搜索的结果) 矩阵中有0(半径中找不到邻居),我想用实际名称替换索引。这样做的简单方法是什么?
Tamas
答案 0 :(得分:0)
也许这可以帮助您:
数据:
set.seed(1337)
m <- matrix(sample(c(0,0,0,1:5), 25, TRUE), 5, 5)
看起来像:
# [,1] [,2] [,3] [,4] [,5]
#[1,] 2 0 5 0 4
#[2,] 2 5 5 5 3
#[3,] 0 0 4 5 0
#[4,] 1 0 0 0 0
#[5,] 0 0 5 0 2
名称向量:
namesVec <- c(0,paste0("name_",1:5))
代码:
m[] <- namesVec[c(m) + 1]
结果如下:
# [,1] [,2] [,3] [,4] [,5]
#[1,] "name_2" "0" "name_5" "0" "name_4"
#[2,] "name_2" "name_5" "name_5" "name_5" "name_3"
#[3,] "0" "0" "name_4" "name_5" "0"
#[4,] "name_1" "0" "0" "0" "0"
#[5,] "0" "0" "name_5" "0" "name_2"