Esempio n. 1
0
def test_find_onlyfromloadedlibrary():
    with pytest.raises(KeyError):
        rinterface.globalenv.find('survfit')
    try:
        rinterface.evalr('library("survival")')
        sfit_R = rinterface.globalenv.find('survfit')
        assert isinstance(sfit_R, rinterface.SexpClosure)
    finally:
        rinterface.evalr('detach("package:survival")')
Esempio n. 2
0
 def __repr__(self):
     # TODO: hack to work around an issue with calling R functions
     #   with rpy2 (language objects seem to be evaluated). Without
     #   the issue, the representation should simply be
     #   ri.baseenv['deparse'](self)[0]
     tmp_r_var = str(uuid.uuid4())
     representation = None
     try:
         ri.globalenv[tmp_r_var] = self
         representation = ri.evalr('deparse(`{}`)'.format(tmp_r_var))[0]
     finally:
         del ri.globalenv[tmp_r_var]
     return 'Rlang( {} )'.format(representation)
Esempio n. 3
0
def test_non_asciil():
    u_char = '\u21a7'
    b_char = b'\xe2\x86\xa7'
    assert (b_char == u_char.encode('utf-8'))
    sexp = ri.StrSexpVector((u'\u21a7', ))
    char = sexp[0]
    assert isinstance(char, str)
    # FIXME: the following line is failing on drone, but not locally
    assert u'\u21a7'.encode('utf-8') == char.encode('utf-8')
    # because of this, the following line is used to pass the test
    # until I have more reports from users or manage to reproduce
    # myself what is happening on drone.io.
    sexp = ri.evalr('c("ěščřžýáíé", "abc", "百折不撓")')
    assert all(isinstance(x, str) for x in sexp)
def test_rclass_get():
    sexp = rinterface.baseenv.find('character')(1)
    assert len(sexp.rclass) == 1
    assert sexp.rclass[0] == 'character'

    sexp = rinterface.baseenv.find('matrix')(0)
    if rinterface.evalr('R.version$major')[0] >= '4':
        assert tuple(sexp.rclass) == ('matrix', 'array')
    else:
        assert tuple(sexp.rclass) == ('matrix', )

    sexp = rinterface.baseenv.find('array')(0)
    assert len(sexp.rclass) == 1
    assert sexp.rclass[0] == 'array'

    sexp = rinterface.baseenv.find('new.env')()
    assert len(sexp.rclass) == 1
    assert sexp.rclass[0] == 'environment'
Esempio n. 5
0
import array
import pytest
import rpy2.rinterface_lib.sexp
from rpy2 import rinterface
from rpy2 import robjects


@pytest.mark.parametrize(
    'cls, values, expected_cls',
    [(rinterface.IntSexpVector, (1, 2), robjects.vectors.IntVector),
     (rinterface.FloatSexpVector, (1.1, 2.2), robjects.vectors.FloatVector),
     (rinterface.StrSexpVector, ('ab', 'cd'), robjects.vectors.StrVector),
     (rinterface.BoolSexpVector, (True, False), robjects.vectors.BoolVector),
     (rinterface.ByteSexpVector, b'ab', robjects.vectors.ByteVector),
     (lambda x: rinterface.evalr(x), 'y ~ x', robjects.Formula)])
def test_sexpvector_to_ro(cls, values, expected_cls):
    v_ri = cls(values)
    v_ro = robjects.default_converter.rpy2py(v_ri)
    assert isinstance(v_ro, expected_cls)


def test_mapperR2Python_function():
    sexp = rinterface.globalenv.find('plot')
    ob = robjects.default_converter.rpy2py(sexp)
    assert isinstance(ob, robjects.Function)

    
def test_mapperR2Python_environment():
    sexp = rinterface.globalenv.find('.GlobalEnv')
    assert isinstance(robjects.default_converter.rpy2py(sexp), 
                      robjects.Environment)
Esempio n. 6
0
# TODO: uuid is used to create a temporary symbol. This is a ugly
#     hack to work around an issue with with calling R functions
#     (language objects seem to be evaluated when doing so from rpy2
#     but not when doing it from R).
import typing
import uuid
from rpy2.robjects import conversion
from rpy2.robjects.robject import RObject
import rpy2.rinterface as ri
_reval = ri.baseenv['eval']
_parse = ri.parse

try:
    _str2lang = ri.baseenv['str2lang']
except KeyError:
    _str2lang = ri.evalr('function(s) parse(text=s, keep.source=FALSE)[[1]]')


def eval(x: str, envir: ri.SexpEnvironment = ri.globalenv) -> ri.Sexp:
    """ Evaluate R code. If the input object is an R expression it
    evaluates it directly, if it is a string it parses it before
    evaluating it.

    By default the evaluation is performed in R's global environment
    but a specific environment can be specified.

    Args:
        x (str): a string to be parsed and evaluated as R code
        envir (rpy2.rinterface.SexpEnvironment): An R environment in
          which to evaluate the R code.
    Returns:
Esempio n. 7
0
def test_R_to_NAReal():
    r_na_real = ri.evalr('NA_real_')[0]
    assert math.isnan(r_na_real)
Esempio n. 8
0
def test_r_to_NAInteger():
    na_int = ri.NA_Integer
    r_na_int = ri.evalr("NA_integer_")[0]
    assert r_na_int is na_int
Esempio n. 9
0
def test_R_to_NALogical():
    r_na_lgl = ri.evalr('NA')[0]
    assert r_na_lgl is ri.NA
Esempio n. 10
0
def test_R_to_NAComplex():
    r_na_complex = ri.evalr('NA_complex_')[0]
    assert math.isnan(r_na_complex.real)
    assert math.isnan(r_na_complex.imag)
Esempio n. 11
0
def test_r_to_NACharacter():
    na_character = ri.NA_Character
    r_na_character = ri.evalr("NA_character_")
    assert r_na_character.typeof == ri.RTYPES.STRSXP
    assert len(r_na_character) == 1
    assert r_na_character.get_charsxp(0).rid == na_character.rid
def test_rclass_get_sym():
    # issue #749
    fit = rinterface.evalr("""
    stats::lm(y ~ x, data=base::data.frame(y=1:10, x=2:11))
    """)
    assert tuple(fit[9].rclass) == ('call', )