[R] Selecting rows/columns of a matrix
William Dunlap
wdunlap at tibco.com
Sun Oct 26 19:56:37 CET 2014
Use logical vectors and the "[" operator: x[condition] can be read as
'x such that condition [is true]'. E.g.,
> a<-matrix(1:16, 4,4,byrow=T)
> j <- c(TRUE, FALSE, TRUE, FALSE)
> a[j,,drop=FALSE]
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 9 10 11 12
> a[,j,drop=FALSE]
[,1] [,2]
[1,] 1 3
[2,] 5 7
[3,] 9 11
[4,] 13 15
> a[j,j,drop=FALSE] # apply t() to the result if you want the transpose
[,1] [,2]
[1,] 1 3
[2,] 9 11
The drop=FALSE is not needed in these examples, but prevents single-row
or -column results from be converted to vectors.
See "An Introduction to R" (under Help>Manuals in the Windows GUI,
or look on the R website) for details on these and many other issues.
Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Sun, Oct 26, 2014 at 11:35 AM, Steven Yen <syen04 at gmail.com> wrote:
> 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.
More information about the R-help
mailing list