R choosing certain elements from the matrix at the same time

Is there a way that I can immediately select a collection of given elements from a matrix? In particular, suppose I have the following matrix:

58 59 60 62 63 64 58 0.000000 3.772139 6.367721 8.978718 12.197210 13.401126 59 3.772139 0.000000 3.755554 5.935946 9.592700 11.664533 60 6.367721 3.755554 0.000000 5.999409 9.324764 11.991269 62 8.978718 5.935946 5.999409 0.000000 3.810169 6.762802 63 12.197210 9.592700 9.324764 3.810169 0.000000 3.796884 64 13.401126 11.664533 11.991269 6.762802 3.796884 0.000000 

I want to select cells [1,2], [2,3], [3,4], [4,5], [5,6]. I understand that I can refer to them by index, in this case I can run:

mymatrix [s (2,9,16,23,30)].

However, this is not very clear by reading the code later. Is there a way that I can immediately enter the actual (row, column) link?

Thanks!

+7
source share
3 answers

Indexing can be performed using two column matrices. After converting these rows and columns to a valid R object (and not Matlab-style):

 > idxs <- gsub("\\]",")", gsub("\\[", "c(", "[1,2], [2,3], [3,4], [4,5] ,[5,6]") ) # I edited the string value that idxs returned: > midx <- rbind( c(1,2), c(2,3), c(3,4), c(4,5) ,c(5,6) ) > mat <- matrix(scan(), nrow=6) 1: 0.000000 3.772139 6.367721 8.978718 12.197210 13.401126 7: 3.772139 0.000000 3.755554 5.935946 9.592700 11.664533 13: 6.367721 3.755554 0.000000 5.999409 9.324764 11.991269 19: 8.978718 5.935946 5.999409 0.000000 3.810169 6.762802 25: 12.197210 9.592700 9.324764 3.810169 0.000000 3.796884 31: 13.401126 11.664533 11.991269 6.762802 3.796884 0.000000 37: Read 36 items > mat[midx] [1] 3.772139 3.755554 5.999409 3.810169 3.796884 

If your goal was to index a super diagonal that could be completed as a whole:

 > mat[col(mat)==row(mat)+1] [1] 3.772139 3.755554 5.999409 3.810169 3.796884 
+12
source

The solution to your specific situation is to select a submatrix and use the diag function:

 R> diag(x[-ncol(x),-1]) [1] 3.772139 3.755554 5.999409 3.810169 3.796884 
+8
source

A similar solution, which was published above, but one that concerns the situation with the vector for rows and the vector for columns (which was my question when I came across this thread), looks like this:

 > rows <- c(1,2,3,4,5) > cols <- c(2,3,4,5,6) > call <- cbind(rows,cols) > > mat[call] [1] 3.772139 3.755554 5.999409 3.810169 3.796884 
+3
source

All Articles