Subsetting a Matrix by Row.Names

Subsetting a matrix by row.names

Set up some fake data:

m <- matrix(1:30, 6, 5)
rownames(m) <- c("X1", "X5", "X33", "X37", "X52", "X566")
m
# [,1] [,2] [,3] [,4] [,5]
# X1 1 7 13 19 25
# X5 2 8 14 20 26
# X33 3 9 15 21 27
# X37 4 10 16 22 28
# X52 5 11 17 23 29
# X566 6 12 18 24 30

Here it's probably easiest to subset with matrix indexing ([):

include_list <- c("X1", "X5", "X33")
m[include_list, ]
# [,1] [,2] [,3] [,4] [,5]
# X1 1 7 13 19 25
# X5 2 8 14 20 26
# X33 3 9 15 21 27

Alternative with subset() function:

subset(m, rownames(m) %in% include_list)
# [,1] [,2] [,3] [,4] [,5]
# X1 1 7 13 19 25
# X5 2 8 14 20 26
# X33 3 9 15 21 27

Subsetting a matrix by row names and column names in R

Try to filter rows and columns in this way:

matrix[rownames(matrix)%in%list_individuals,colnames(matrix)%in%list_individuals]

Only rows and columns contained in list_individuals will be mantained in the output.

How to subset and reorder a matrix based on the row names of other matrix

You will get a lot more help if you share reproducible examples. You can use the dput( ) function to help share your data.

you can subset with this code:

marker[row.names(marker) %in% row.names(pheno),]

How do I subset a matrix by rownames using a list of row headers

A great place to look would be Hadley's page on subsetting in R.

In terms of a specific answer to the question, let's assume that you have an original list of rownames that you would like to subset on that is called 'mylist'. You could do the following:

index <- row.names(bigfile)  %in% mylist[,1] 

This should give a boolean expression that is as long as the number of rows in the bigfile.

EDIT: You might also look at the following Stackoverflow post which nicely addresses the problem.

R // subset matrix rows and columns based on names

You may also subset for names.

y <- x[c("a", "c"), c("a", "c")]
y
# a c
# a 2 5
# c 4 7

Or, using subset

y <- subset(x, colnames(x) %in% c("a", "c"), 
rownames(x) %in% c("a", "c"))
y
# a c
# a 2 5
# c 4 7

R - Subset a list of matrices by rowname

To be able to get what you expect use this code:

 lapply(mtx_list,function(x) x[row.names(x)%in%c("B","D"),])
[[1]]
[,1] [,2] [,3]
B 2 6 10
D 4 8 12

[[2]]
[,1] [,2] [,3]
B 14 18 22
D 16 20 24

subsetting a data frame according to specific pattern

Of course you are able to use subset, i.e.,

res <- subset(fru,grepl("a",rownames(fru)))

subsetting 1-column matrix deletes rownames

you can read about argument drop in the help page: ?'['

M[which(rownames(M) != "A"), ,drop=FALSE]


Related Topics



Leave a reply



Submit