0
votes

I have made a matrix where each element in the matrix is a vector of two numbers. Now I want to rank all the vectors inside, so I get the rank of the vectors as the new vector elements of the matrix.

Here is an example of the code:

listwvectors <- vector("list")
t=1
for (i in 1:3) {
  for (j in 1:5) {
    listwvectors[[t]] <- c(i,j)
    t=t+1
  }
}
print(listwvectors)

testmatrix <- matrix(data=listwvectors, nrow=5, ncol=3)
print(testmatrix)

rank(testmatrix[1,1])

The last part ("rank(testmatrix[1,1])") just give 1. Why is that? I want it to print the ranked vector. So in fact, I want to make a new matrix that has the same mode as the testmatrix but the vectors inside is the ranked vectors of the testmatrix.

Hope you understand what I am trying to ask. Thanks in advance!:)

2
Hi Monica. Could you add a minimal reproducible example? It will make it easier for others to find and test a answer to your question. That way you can help others to help you! - dario
Yes here is an example you can try. listwvectors <- vector("list") t=1 for (i in 1:3) { for (j in 1:5) { listwvectors[[t]] <- c(i,j) t=t+1 } } print(listwvectors) testmatrix <- matrix(data=listwvectors, nrow=5, ncol=3) print(testmatrix) rank(testmatrix[1,1]) - Monica
To answer your question "Why is that?": testmatrix[1,1] is a list. Its first element is a vector. If you want to use this first element of the list you have to do : testmatrix[1,1][[1]] - jogo
Oh that is so helpful! Thanks a lot! Do you know how I then can go through all the vectors in the testmatrix to get all vectors ranked? I have no idea how i then can make a for loop if i need to use both [1,1] and [1]. What is the next vector in the matrix than? is it [1,1][2] or is it [1,2][1] for example? in other words, is there always [1] in the last bracket? - Monica
to access the content of the i-th element of a list in R we use [[i]], ofr example rank(testmatrix[1,1][[1]]) returns [1] 1.5 1.5 - dario

2 Answers

-1
votes

minimal example data:

m <- matrix(list(c(1,3), c(2,1), c(2,2), c(1,2)), ncol=2)
        [, 1]    [, 2]
[1, ] c(1, 3)  c(2, 2) 
[2, ] c(2, 1)  c(1, 2)

Solution 1 using apply (returns '3d matrix'):

apply(apply(m, c(1,2), function(x) rank(x[[1]]))

Solution 2 using loop (returns '2d matrix' of lists):

result <- m # copy original matrix as template to recieve rankings
for (i in seq_along(m[, 1])) {
  for (j in seq_along(m[1, ])) {
    result[i, j][[1]] <- rank(m[i, j][[1]])
  }
}
-2
votes

since there is only one vector inside a matrix, you can use rank(my_matrix)