Home > Blockchain >  R: Vector to matrix - convert one-dimensional vector index to two-dimensional matrix index?
R: Vector to matrix - convert one-dimensional vector index to two-dimensional matrix index?

Time:01-15

Let's say I have a vector:

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

And for some reason index, say, 9 in that vector (having value 1) is important to me:

> myVector[9]
[1] 1

For some another reason, I want to make this vector a matrix with dimensions 6x2 (six rows, two columns).

> 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

Now I would like to know where my vector index 9 is located at in this new matrix. How do I get that information?

Of course, I can see in this case that it is row number 3 and column number 2, but how do I know in general where do the parameters of the transformation (number of rows and columns in the matrix) take my original index?

CodePudding user response:

The matrix you are creating still incorporates the vector it was build on, so indexing should still work.

myVector <- c(1,2,3,4,1,2,3,4,1,2,3,4)
myMatrix <- matrix(myVector, nrow = 6, ncol = 2)
# check pos 9
myMatrix[9] # 1
myVector[9] # 1
# check all positions:
myMatrix==myVector # all true

# or manually:
for (i in seq_along(myVector)) {
  print(myMatrix[i]==myVector[i])
}

CodePudding user response:

After giving myself some time to think this, I figured out that this can be solved with some algebra:

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) 

And the print out is as it should:

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