user2726449
user2726449

Reputation: 627

Deleting columns and rows from a matrix by name [R]

I have a kinship matrix, which is essentially a list of IDs down and the same IDs across, like so:

ID1  ID2  ID3  ID4  ID5  ID6
ID2
ID3
ID4
ID5
ID6

And so on. I would like to eliminate certain IDs from the matrix (that is, deleting the columns and the rows that of the IDs I don't want). My matrix is 129 x 129 and my ID list that I want to keep is 60 IDs long. I have tried the following code (with dummy data):

kinstmp <- matrix(c(0,0,1,0,1,0,
     0,0,1,0,0,0,
     0,1,1,1,0,0,
     1,0,1,0,0,0,
     0,0,1,0,1,0,
     0,0,1,0,0,0,
     0,1,1,1,0,0), nrow=6) #example of what my matrix looks like
kinstmp2 <- kinstmp[rownames(kinstmp) %in% id, ]
kins <- kinstmp2[,colnames(kinstmp2) %in% id ]

However, this results in no rows and columns being deleted. Is there a way to get this to work?

An example of the id file is:

ID3
ID5
ID6

Upvotes: 1

Views: 1205

Answers (1)

Henrik
Henrik

Reputation: 67828

You need to add dimnames to your matrix, and make sure place the column condition on the right (literally) side of the comma.

nm <- paste0("ID", 1:6)
kinstmp <- matrix(c(0,0,1,0,1,0,
                    0,0,1,0,0,0,
                    0,1,1,1,0,0,
                    1,0,1,0,0,0,
                    0,0,1,0,1,0,
                    0,0,1,0,0,0), nrow = 6, dimnames = list(nm, nm))
kinstmp

id <- c("ID3", "ID5", "ID6")

# subsetting rows
kinstmp2 <- kinstmp[!rownames(kinstmp) %in% id, ]
kinstmp2
#     ID1 ID2 ID3 ID4 ID5 ID6
# ID1   0   0   0   1   0   0
# ID2   0   0   1   0   0   0
# ID4   0   0   1   0   0   0

# subsetting columns
kins <- kinstmp2[ , !colnames(kinstmp2) %in% id]
kins
#     ID1 ID2 ID4
# ID1   0   0   1
# ID2   0   0   0
# ID4   0   0   0

# or subsetting rows and columns in one call
kinstmp[!rownames(kinstmp) %in% id, !colnames(kinstmp2) %in% id]

Upvotes: 2

Related Questions