Reputation: 6561
I would like to test if the column names of a matrix are contained within the rownames of a matrix i.e. if colnames(abun) and contained within rownames(x) in example below
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
UPDATE: I am writing a function and would like an error message to be thrown if a colnames(abun) is not contained within rownames(x). I have tried:
if(colnames(abun) %in% rownames(x) = FALSE)
stop("species names in abun and x do not match")
Upvotes: 0
Views: 2049
Reputation: 121568
Are you just asking for the intersection of 2 sets?
intersect(c("A","B","C","D") ,
c("A","B","C"))
[1] "A" "B" "C"
To get the difference use setdiff
:
setdiff(c("A","B","C","D") ,
c("A","B","C"))
[1] "D"
Upvotes: 1
Reputation: 12875
colnames(abun)[
colnames(abun) %in% rownames(x)
]
colnames(abun) %in% rownames(x)
returns a true/false vector indicating which element on colnames(abun)
is present in rownames(x)
.
Upvotes: 1