[R] Extracting selected rows from a matrix
Kjetil Halvorsen
kjetilbrinchmannhalvorsen at gmail.com
Tue Nov 30 01:05:36 CET 2010
see below.
On Mon, Nov 29, 2010 at 5:56 PM, pankaj borah
<pankajborah2k3 at yahoo.co.in> wrote:
> Hi,
>
> I have matrix of 104 columns and 30000 rows (Each Row has rowname).
>
> I have 13 different list of selected rownames (character) say 1000 each. Now I want to extract the all the columns according to the rownames in each the list.
>
if those are lists, make them vectors by calling unlist().
then:
> How can I do that in R ?
>
> 1 ) For a single list
Look at this example:
> mat <- matrix(1:100, 10, 10)
> head(mat)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
> rownames(mat)
NULL
> rownames(mat) <- 1:10
> rownames(mat)
[1] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10"
> mat
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
1 1 11 21 31 41 51 61 71 81 91
2 2 12 22 32 42 52 62 72 82 92
3 3 13 23 33 43 53 63 73 83 93
4 4 14 24 34 44 54 64 74 84 94
5 5 15 25 35 45 55 65 75 85 95
6 6 16 26 36 46 56 66 76 86 96
7 7 17 27 37 47 57 67 77 87 97
8 8 18 28 38 48 58 68 78 88 98
9 9 19 29 39 49 59 69 79 89 99
10 10 20 30 40 50 60 70 80 90 100
> mat[rownames(mat)==7, ]
[1] 7 17 27 37 47 57 67 77 87 97
> mat[rownames(mat)%in%c(7, 5,3), ]
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
3 3 13 23 33 43 53 63 73 83 93
5 5 15 25 35 45 55 65 75 85 95
7 7 17 27 37 47 57 67 77 87 97
>
> 2) For all the 13 list at a time
use a for loop.
Kjetil
>
> Regards,
>
> Pankaj Barah
> Department of Biology,
> Norwegian University of Science & Technology (NTNU)
>
>
>
> [[alternative HTML version deleted]]
>
>
> ______________________________________________
> 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