[R] Selecting rows/columns of a matrix

Steven Yen syen04 at gmail.com
Sun Oct 26 19:57:05 CET 2014


Rui

Thanks. This works great. Below, I get the 2nd, 4th, and 6th rows/columns:

 > (a<-matrix(1:36,6,6))
      [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    7   13   19   25   31
[2,]    2    8   14   20   26   32
[3,]    3    9   15   21   27   33
[4,]    4   10   16   22   28   34
[5,]    5   11   17   23   29   35
[6,]    6   12   18   24   30   36
 > (j<-matrix(c(0,1,0,1,0,1)))
      [,1]
[1,]    0
[2,]    1
[3,]    0
[4,]    1
[5,]    0
[6,]    1
 > ((a[as.logical(j), as.logical(j)]))
      [,1] [,2] [,3]
[1,]    8   20   32
[2,]   10   22   34
[3,]   12   24   36

Steven Yen

At 02:49 PM 10/26/2014, Rui Barradas wrote:
>Sorry, that should be
>
>t(a[as.logical(j), as.logical(j)])
>
>Rui Barradas
>
>Em 26-10-2014 18:45, Rui Barradas escreveu:
>>Hello,
>>
>>Try the following.
>>
>>a[as.logical(j), as.logical(j)]
>>
>># or
>>b <- a[as.logical(j), ]
>>t(b)[as.logical(j), ]
>>
>>
>>Hope this helps,
>>
>>Rui Barradas
>>
>>Em 26-10-2014 18:35, Steven Yen escreveu:
>>>Dear
>>>
>>>I am interested in selecting rows and columns of a matrix with a
>>>criterion defined by a binary indicator vector. Let  matrix a be
>>>
>>>  > a<-matrix(1:16, 4,4,byrow=T)
>>>  > a
>>>       [,1] [,2] [,3] [,4]
>>>[1,]    1    2    3    4
>>>[2,]    5    6    7    8
>>>[3,]    9   10   11   12
>>>[4,]   13   14   15   16
>>>
>>>Elsewhere in Gauss, I select the first and third rows and columns of a
>>>by defining a column vector j = [1,0,1,0]. Then, select the rows of a
>>>using j, and then selecting the rows of the transpose of the resulting
>>>matrix using j again. I get the 2 x 2 matrix as desired. Is there a way
>>>to do this in R? below are my Gauss commands. Thank you.
>>>
>>>---
>>>
>>>j
>>>
>>>1
>>>0
>>>1
>>>0
>>>
>>>a=selif(a,j); a
>>>
>>>1  2  3  4
>>>9 10 11 12
>>>
>>>a=selif(a',j); a
>>>
>>>1  9
>>>3 11
>>>
>>>______________________________________________
>>>R-help at r-project.org mailing list
>>>https://stat.ethz.ch/mailman/listinfo/r-help
>>>PLEASE do read the posting guide
>>>http://www.R-project.org/posting-guide.html
>>>and provide commented, minimal, self-contained, reproducible code.
>>
>>______________________________________________
>>R-help at r-project.org mailing list
>>https://stat.ethz.ch/mailman/listinfo/r-help
>>PLEASE do read the posting guide
>>http://www.R-project.org/posting-guide.html
>>and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list