2
votes

I want to subset a large matrix (columns and rows) based on a list input (which will change dynamically). Example (see reproducible example below): I have a symmetric matrix (x) and a list containing the rows and column I want to have in my subset (categories). How do I subset rows and columns so that my results only shows rows & columns for a and c (see desired output)

categories = c("a", "c")

a = c(2,3,4)
b = c(1,9,8)
c = c(5,6,7)

x = cbind(a,b,c)
rownames(x) <- c("a", "b", "c")
x = as.matrix(x)

# attempt: 
result = x[x %in% categories == TRUE]

desired output 
a = c(2,4)
c = c(5,7)
y = cbind(a,c)
rownames(y) <- c("a", "c")
y = as.matrix(y)
1

1 Answers

1
votes

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