[datatable-help] Selecting rows (rownames) and colnames of a matrix

Steven C. Bagley steven.bagley at gmail.com
Thu Jan 26 16:30:56 CET 2012


Peter:

This mailing list is only for the data.table package, not for general help with matrices or data frames. You should ask r-help or other general R related lists for help.

But here's an answer anyhow:

I'm a bit puzzled by your question as stated. All of the rows of your matrix have at least one element greater than 7, so all are selected by the expression you wrote. Here are some variations which may help you out:

> rownames(m)[ apply(m, 1, function(x) any(x > 7)) ]
[1] "M1" "M2" "M3"
> rownames(m)[ apply(m, 1, function(x) any(x > 11)) ]
[1] "M3"
> (1:nrow(m))[ apply(m, 1, function(x) any(x > 11)) ]
[1] 3
> apply(m, 1, function(x) any(x > 11))
   M1    M2    M3 
FALSE FALSE  TRUE 

--Steve

On Jan 26, 2012, at 6:48 AM, ZoliTeglas wrote:

> Dear all, 
> I am looking for a workaround to select rows and cols of a matrix. 
> I want to select all rows which have a value higher than a threshold. 
> 
> If i create my matrix with 
> 
> 
> m <- matrix(1:12,3,4) 
> I get 
>     [,1] [,2] [,3] [,4] 
> [1,]    1    4    7   10 
> [2,]    2    5    8   11 
> [3,]    3    6    9   12 
> 
> Let's give the matrix rownames  with 
> rownames(m) <- c("M1", "M2", "M3") 
> 
> I get my matrix 
> 
>   [,1] [,2] [,3] [,4] 
> M1    1    4    7   10 
> M2    2    5    8   11 
> M3    3    6    9   12 
> 
> No I want to select the rownames of m which have a value higher than 7 in a
> row 
> 
> I tried 
> m[apply(m, 1, function(x) any(x > 7)),] 
> 
> but the return was the whole matrix. So it was not possible for me to get
> the two last columns.... 
> 
> Is there any easy way to get the index or rowname  of a matrix which have an
> entry with a chosen threshold? 
> 
> Would be nice if anybody can help me out. 
> 
> All the best 
> Peter 
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/Selecting-rows-rownames-and-colnames-of-a-matrix-tp4330511p4330511.html
> Sent from the datatable-help mailing list archive at Nabble.com.
> _______________________________________________
> datatable-help mailing list
> datatable-help at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help



More information about the datatable-help mailing list