It is fairly common to see code that looks like:
if( sum( rowNameToFind %in% rownames(mat)) ) { TRUE }else{ FALSE }
This deals simultaneously with the rownames-missing-entirely possibility at the same time as target-not-in-rownames.
Question
I have a matrix in which each row vector has a name. I would like to check row membership in my matrix, that is I would like to turn the following into R code:
if(mat contains "rowname")
{ do appropriate task ....}
else if(mat contains "otherrowname")
{ do appropriate task ....}
else
{ do different task....}
All help is appreciated!
Solution
It is fairly common to see code that looks like:
if( sum( rowNameToFind %in% rownames(mat)) ) { TRUE }else{ FALSE }
This deals simultaneously with the rownames-missing-entirely possibility at the same time as target-not-in-rownames.
OTHER TIPS
A matrix may or may not have rownames
for you to index. You can index them with the %in%
operator. Here's a quick example:
#Sample matrix
mat <- matrix(rnorm(100), ncol = 10)
#Find the row 'b'
rowNameToFind <- "b"
if (is.null(rownames(mat))) {
print("no rownames to index!")
} else if (rowNameToFind %in% rownames(mat)) {
print("hurrary")
} else {
print("boo")
}
#Returns
[1] "no rownames to index!"
#Define the rownames
rownames(mat) <- letters[1:10]
if (is.null(rownames(mat))) {
print("no rownames to index!")
} else if (rowNameToFind %in% rownames(mat)) {
print("hurrary")
} else {
print("boo")
}
#Returns
[1] "hurrary"
As long as each row has a rowname you can do the following:
> if("somerowname" %in% rownames(somematrix))
+ { print("true") } else print("false")
[1] "true"
I hope this helps and that the code is clear!