A simple "is there a better way" question. I want to find if any cell in a data.frame contains the sub-string I'm looking for:
d=data.frame(V1=c("xxx","yyy","zzz"), V2=c(NA,"ewruinwe",NA))
grepl("ruin",d[2,2]) #TRUE
grepl("ruin",d) #FALSE FALSE
any(grepl("ruin",as.character(as.matrix(d)))) #TRUE
The last line does what I want, but it looks so ugly I'm wondering if I'm missing something simpler.
Background: d
is one of the elements in t=readHTMLTable(url)
(XML package). I was doing the d[2,2] approach, to check for an error message, and just discovered the website sometimes add another row to the HTML table, pushing the error message I was looking for to another cell.
UPDATE: so, it seems the two choices (thanks to mathematical.coffee and Roman Luštrik) are:
any(grepl("ruin",as.matrix(d)))
any(apply(d, 2, function(x) grepl("ruin", x)))
What about this?
d=data.frame(V1=c("xxx","yyy","zzz"), V2=c(NA,"ewruinwe",NA))
apply(d, c(1,2), function(x) grepl("ruin", x))
V1 V2
[1,] FALSE FALSE
[2,] FALSE TRUE
[3,] FALSE FALSE
As noted in the comments "2" does the same as "c(1,2)". Then to give a single boolean value:
any(apply(d, 2, function(x) grepl("ruin", x)))
[1] TRUE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With