Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

suppress warnings in rpy2

When I import R in python, using rpy2, how do I suppress warnings?

It appears that in R you have to do just the following

options(warn=-1)

...but I'm not familiar with R. How do I do this in python?

like image 873
Ricky Robinson Avatar asked Aug 16 '12 17:08

Ricky Robinson


3 Answers

The warning system in rpy2 uses Python's warnings module. As a consequence, you can switch off warnings using that package's filterwarnings() function. As already pointed out in a comment to another answer here this could be dangerous as not only R-related warnings are affected.

However, rpy2 comes with its own warning class, RRuntimeWarning. Therefore, you can switch off only this type of warning by

import warnings
from rpy2.rinterface import RRuntimeWarning
warnings.filterwarnings("ignore", category=RRuntimeWarning)
like image 117
applesoup Avatar answered Oct 23 '22 10:10

applesoup


Beginning with 3.0 version, rpy2 does not use Python's warnings module anymore. It now relies on logging instead. The new solution would be:

from rpy2.rinterface_lib.callbacks import logger as rpy2_logger
import logging
rpy2_logger.setLevel(logging.ERROR)   # will display errors, but not warnings

If you want to filter specific warnings only, use:

rpy2_logger.addFilter(lambda record: 'notch went outside hinges' not in record.msg)

See LogRecord class specification for available fields for advanced filtering.

like image 22
krassowski Avatar answered Oct 23 '22 09:10

krassowski


You pretty much gave the answer yourself. You can call the options(warn=-1) function from Python by using RPy:

rpy.r['options'](warn=-1)

For RPy2 it should be something like this (haven't tried this):

rpy2.robjects.r['options'](warn=-1)

Just put it at the beginning of your Python script (after the module imports) and all warnings should be suppressed.

like image 2
Serrano Avatar answered Oct 23 '22 08:10

Serrano