按名称从矩阵中删除列和行[R]

时间:2014-04-29 21:26:53

标签: r matrix

我有一个亲属矩阵,它本质上是一个ID列表和相同的ID,如下所示:

ID1  ID2  ID3  ID4  ID5  ID6
ID2
ID3
ID4
ID5
ID6

等等。我想从矩阵中删除某些ID(即删除我不想要的ID列和行)。我的矩阵是129 x 129,我要保留的ID列表是60个ID长。我尝试了以下代码(使用虚拟数据):

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 ]

但是,这会导致不删除任何行和列。有没有办法让这个工作?

id文件的一个例子是:

ID3
ID5
ID6

1 个答案:

答案 0 :(得分:1)

您需要将dimnames添加到矩阵中,并确保将列条件放在逗号的右侧(字面)。

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]