user3495408
user3495408

Reputation: 11

Extract values at row r and column n-1 in matrix in R

I'd like to return a list of some values within my matrix. Essentially I would be looking to extract values at

[2,1]
[5,4]
[8,7]
and so on. 

Basically, every third row beginning at row n=2, and the corresponding value in column n-1.

It seems simple, but I can't wrap my head around it.

My matrix is 141x141. This output should yield 47 values.

Upvotes: 1

Views: 812

Answers (1)

989
989

Reputation: 12937

You can try this:

m <- matrix(1:100, ncol = 10, byrow = T) # some toy data   
s <- seq(2, nrow(m), 3)
m[cbind(s,s-1)]

#[1] 11 44 77

m

#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,]    1    2    3    4    5    6    7    8    9    10
# [2,]   11   12   13   14   15   16   17   18   19    20
# [3,]   21   22   23   24   25   26   27   28   29    30
# [4,]   31   32   33   34   35   36   37   38   39    40
# [5,]   41   42   43   44   45   46   47   48   49    50
# [6,]   51   52   53   54   55   56   57   58   59    60
# [7,]   61   62   63   64   65   66   67   68   69    70
# [8,]   71   72   73   74   75   76   77   78   79    80
# [9,]   81   82   83   84   85   86   87   88   89    90
#[10,]   91   92   93   94   95   96   97   98   99   100

Upvotes: 1

Related Questions