R:向量将一维向量索引转换为二维矩阵索引?



假设我有一个向量:

myVector <- c(1,2,3,4,1,2,3,4,1,2,3,4)

由于某种原因,比如,向量中的索引9(值为1)对我来说很重要:

> myVector[9]
[1] 1

出于另一个原因,我想让这个向量成为一个维度为6x2(六行两列)的矩阵。

> myMatrix <- matrix(myVector, nrow = 6, ncol = 2)  # Only either nrow or ncol argument is actually required.
> myMatrix
[,1] [,2]
[1,]    1    3
[2,]    2    4
[3,]    3    1
[4,]    4    2
[5,]    1    3
[6,]    2    4

现在我想知道我的向量索引9在这个新矩阵中的位置。我怎么得到这些信息?

当然,在这种情况下,我可以看到它是第3行和第2列,但我怎么知道在一般情况下,转换的参数(矩阵中的行数和列数)在哪里取我的原始索引?

您可以使用arrayInd():

arrayInd(9, .dim = dim(myMatrix))
[,1] [,2]
[1,]    3    2

在给自己一些时间思考之后,我发现这可以用一些代数来解决:

originalIndex <- 9 # this is the index in the original vector
nrows <- 6 # number of rows in the matrix to be created
rowIndex = originalIndex - (ceiling(originalIndex / nrows) - 1) * nrows
columnIndex = ceiling(originalIndex / nrows) 

打印结果如下:

> rowIndex
[1] 3
> columnIndex
[1] 2

您正在创建的矩阵仍然包含它所构建的向量,因此索引应该仍然有效。

myVector <-seq(10,120,10)
myMatrix <- matrix(myVector, nrow = 6, ncol = 2)
# check
myMatrix[3,2]
myVector[9]
# check all positions:
all(myMatrix==myVector)

添加:

为了将奇异数组的索引转换为一对索引i,j,我写了这个函数:[也许有一个更优雅的方法来解决这个问题。]

取矩阵M的奇异索引v_i,对矩阵M进行第一维i的模运算,边缘情况是结果为0,那么我们用i代替模结果。[这是通过ifelse语句实现的]

对于第二个索引jv_i简单地除以i并舍入到下一个整数。

# This small functions converts the singular array index to
# a matrix index i,j based on the dimensions of the input matrix
M_ind <- function(v_i,M) {
i = dim(M)[1]
i_m = ifelse(v_i%%i,v_i%%i,i)
return(c(i_m,ceiling(v_i/i)))
}
## test
test<-M_ind(7,myMatrix)
test
myMatrix[test[1],test[2]]
## Another matrix
myVec<-LETTERS[1:24]
myMat<-matrix(myVec,4,6)
myVec[16] # "P"
test<-M_ind(16,myMat)
test
myMat[test[1],test[2]] #"P"