3

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 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

I used the subset version and it worked perfectly! Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.