测试col名称是否在R中的行名称中

时间:2013-10-02 08:12:36

标签: r match

我想测试一个矩阵的列名是否包含在矩阵的rownames中,即如果colnames(abun)和包含在rownames(x)中的示例如下

abun <- matrix(c(0.4,0,0.6,0.1,0.4,0.5), 
    nrow = 2, ncol = 3, byrow = TRUE, dimnames = list(c("x", "y"), 
    c("A","B","C")))

 abun
    A   B   C
x 0.4 0.0 0.6
y 0.1 0.4 0.5

x<-data.frame("Trait1" =c(1,1,0,1),
                    "Trait2"=c(1,1,1,1),
                    "Trait3" =c(1,1,0,1),
                    "Trait4" =c(1,0,1,1))
rownames(x)<-c("A","B","C","D") 

x
  Trait1 Trait2 Trait3 Trait4
A      1      1      1      1
B      1      1      1      0
C      0      1      0      1
D      1      1      1      1               

更新: 我正在编写一个函数,如果rownames(x)中没有包含colnames(abun),则会抛出一条错误消息。我试过了:

if(colnames(abun) %in% rownames(x) = FALSE)
stop("species names in abun and x do not match")

2 个答案:

答案 0 :(得分:1)

colnames(abun)[
colnames(abun) %in% rownames(x)
]

colnames(abun) %in% rownames(x)返回一个true / false向量,指示colnames(abun)rownames(x)上的哪个元素。

答案 1 :(得分:1)

你只是要求两套交叉吗?

intersect(c("A","B","C","D") ,
          c("A","B","C"))
[1] "A" "B" "C"

要获得差异,请使用setdiff

setdiff(c("A","B","C","D") ,
          c("A","B","C"))
[1] "D"