abrar
abrar

Reputation: 101

How to capture particular warning message and execute call

Lately when I run my code that uses coxph in the survival package coxph(frml,data = data), I am now getting warning messages of the following type

1: In model.matrix.default(Terms, mf, contrasts = contrast.arg) : partial argument match of 'contrasts' to 'contrasts.arg'

2: In seq.default(along = temp) : partial argument match of 'along' to 'along.with'"

I'm not exactly sure why all of a sudden these partial argument match warnings started popping up, but I don't think they effect me.

However, when I get the following warning message, I want coxph(frml,data = data) = NA

3: In fitter(X, Y, strats, offset, init, control, weights = weights, : Loglik converged before variable 2 ; beta may be infinite.

6: In coxph(frml, data = data) : X matrix deemed to be singular; variable 1 3 4

I used tryCatch when I wasn't getting the partial argument match warning using this code where if the nested tryCatch got either a warning or error message it would return NA

coxphfit = tryCatch(tryCatch(coxph(frml,data = data), error=function(w) return(NA)), warning=function(w) return(NA))

However, now that I am getting the partial argument match warnings, I need to only return an NA if there is an error or if I get the above warning messages 3 and 4 . Any idea about how to capture these particular warning messages and return an NA in those instances?

Upvotes: 1

Views: 361

Answers (1)

Konrad
Konrad

Reputation: 18585

It's actually interesting question, if you are looking for quick and dirty way of capturing warnings you could simply do:

   withCallingHandlers({
    warning("hello")
    1 + 2
}, warning = function(w) {
    w ->> w 
}) -> res

In this example the object w created in parent environment would be:

>> w
<simpleWarning in withCallingHandlers({    warning("hello")    1 + 2}, warning = function(w) {    w <<- w}): hello>

You could then interrogate it:

grepl(x = w$message, pattern = "hello")
# [1] TRUE

as

>> w$message
# [1] "hello"

Object res would contain your desired results:

>> res
[1] 3

It's not the super tidy way but I reckon you could always reference object w and check if the warning message has the phrase you are interested in.

Upvotes: 2

Related Questions