0

我想测试矩阵的列名是否包含在矩阵的行名中,即 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               

更新:我正在编写一个函数,如果 colnames(abun) 不包含在 rownames(x) 中,我希望抛出错误消息。我努力了:

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

2 回答 2

1

你只是问2套的交集吗?

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"
于 2013-10-02T08:26:31.173 回答
1
colnames(abun)[
colnames(abun) %in% rownames(x)
]

colnames(abun) %in% rownames(x)返回一个真/假向量,指示 上的哪个元素colnames(abun)存在于 中rownames(x)

于 2013-10-02T08:16:17.863 回答