Reputation: 93
This might sound quite silly but it's driving me nuts. I have a matrix that has alphanumeric values and I'm struggling to test if some elements of that matrix match only the initial and final letters. As I don't care the middle character, I'm trying (withouth success) to use a wildcard.
As an example, consider this matrix:
m <- matrix(nrow=3,ncol=3)
m[1,]=c("NCF","NBB","FGF")
m[2,]=c("MCF","N2B","CCD")
m[3,]=c("A3B","N4F","MCP")
I want to evaluate if m[2,2] starts with "N" and ends with "B", regardless of the 2nd letter in the string. I've tried something like
grep("N.B",m)
and it works, but still I want to know if there is a more compact way of doing it, like:
m[2,2]="N.B"
which ovbiously didn't work!
Thanks
Upvotes: 2
Views: 929
Reputation: 39657
You can use grepl
with the subseted m
like:
grepl("^N.B$", m[2,2])
#[1] TRUE
or use startsWith
and endsWith
:
startsWith(m[2,2], "N") & endsWith(m[2,2], "B")
#[1] TRUE
Upvotes: 1