Пример #1
0
 def __init__(self, formula, environment=rinterface.globalenv):
     if isinstance(formula, str):
         inpackage = rinterface.baseenv["::"]
         asformula = inpackage(rinterface.StrSexpVector([
             'stats',
         ]), rinterface.StrSexpVector([
             'as.formula',
         ]))
         formula = rinterface.SexpVector(
             rinterface.StrSexpVector([
                 formula,
             ]))
         robj = asformula(formula, env=environment)
     else:
         robj = formula
     super(Formula, self).__init__(robj)
Пример #2
0
def set_accessors(cls, cls_name, where, acs):
    # set accessors (to be abandonned for the metaclass above ?)

    if where is None:
        where = rinterface.globalenv
    else:
        where = "package:" + str(where)
        where = rinterface.StrSexpVector((where, ))

    for r_name, python_name, as_property, docstring in acs:
        if python_name is None:
            python_name = r_name
        r_meth = getmethod(rinterface.StrSexpVector((r_name, )),
                           signature=rinterface.StrSexpVector((cls_name, )),
                           where=where)
        r_meth = conversion.ri2py(r_meth)
        if as_property:
            setattr(cls, python_name, property(r_meth, None, None))
        else:
            setattr(cls, python_name, lambda self: r_meth(self))
Пример #3
0
    def __init__(self, obj):
        if not isinstance(obj, rinterface.Sexp):
            #sanity check
            for elt in obj:
                if not inherits(elt, time.struct_time):
                    raise ValueError("""
When giving a Python sequence, all elements must inherit from time.struct_time"""
                                     )
            #convert to an R POSIXlt structure
            obj = rinterface.StrSexpVector(obj)
        pass
Пример #4
0
 def __init__(self,
              obj,
              levels=rinterface.MissingArg,
              labels=rinterface.MissingArg,
              exclude=rinterface.MissingArg,
              ordered=rinterface.MissingArg):
     if not isinstance(obj, rinterface.Sexp):
         obj = rinterface.StrSexpVector(obj)
     res = self._factor(obj,
                        levels=levels,
                        labels=labels,
                        exclude=exclude,
                        ordered=ordered)
     self.__sexp__ = res.__sexp__
     self.ro = VectorOperationsDelegator(self)
     self.rx = ExtractDelegator(self)
     self.rx2 = DoubleExtractDelegator(self)
Пример #5
0
from rpy3.robjects.robject import RObjectMixin
import rpy3.rinterface as rinterface
import conversion

getmethod = rinterface.baseenv.get("getMethod")

require = rinterface.baseenv.get('require')
require(rinterface.StrSexpVector(('methods', )),
        quiet=rinterface.BoolSexpVector((True, )))


class RS4(RObjectMixin, rinterface.SexpS4):
    """ Python representation of an R instance of class 'S4'. """
    def slotnames(self):
        """ Return the 'slots' defined for this object """
        return methods_env['slotNames'](self)

    def do_slot(self, name):
        return conversion.ri2py(super(RS4, self).do_slot(name))

    @staticmethod
    def isclass(name):
        """ Return whether the given name is a defined class. """
        name = conversion.py2ri(name)
        return methods_env['isClass'](name)[0]

    def validobject(self, test=False, complete=False):
        """ Return whether the instance is 'valid' for its class. """
        test = conversion.py2ri(test)
        complete = conversion.py2ri(complete)
        return methods_env['validObject'](self, test=test,
Пример #6
0
class DataFrame(Vector):
    """ R 'data.frame'.
    """
    _dataframe_name = rinterface.StrSexpVector(('data.frame', ))
    _read_csv = utils_ri['read.csv']
    _write_table = utils_ri['write.table']
    _cbind = rinterface.baseenv['cbind.data.frame']
    _rbind = rinterface.baseenv['rbind.data.frame']

    def __init__(self, tlist):
        """ Create a new data frame.

        :param tlist: rpy2.rlike.container.TaggedList or rpy2.rinterface.SexpVector (and of class 'data.frame' for R)
        """
        if isinstance(tlist, rlc.TaggedList):
            df = baseenv_ri.get("data.frame").rcall(tlist.items(),
                                                    globalenv_ri)
            super(DataFrame, self).__init__(df)
        elif isinstance(tlist, rinterface.SexpVector):
            if tlist.typeof != rinterface.VECSXP:
                raise ValueError("tlist should of typeof VECSXP")
            if not globalenv_ri.get('inherits')(tlist,
                                                self._dataframe_name)[0]:
                raise ValueError('tlist should of R class "data.frame"')
            super(DataFrame, self).__init__(tlist)
        elif isinstance(tlist, dict):
            kv = [(k, conversion.py2ri(v)) for k, v in tlist.iteritems()]
            kv = tuple(kv)
            df = baseenv_ri.get("data.frame").rcall(kv, globalenv_ri)
            super(DataFrame, self).__init__(df)
        else:
            raise ValueError(
                "tlist can be either " +
                "an instance of rpy2.rlike.container.TaggedList," +
                " or an instance of rpy2.rinterface.SexpVector" +
                " of type VECSXP, or a Python dict.")

    def _get_nrow(self):
        """ Number of rows. 
        :rtype: integer """
        return baseenv_ri["nrow"](self)[0]

    nrow = property(_get_nrow, None, None)

    def _get_ncol(self):
        """ Number of columns.
        :rtype: integer """
        return baseenv_ri["ncol"](self)[0]

    ncol = property(_get_ncol, None, None)

    def _get_rownames(self):
        res = baseenv_ri["rownames"](self)
        return conversion.ri2py(res)

    def _set_rownames(self, rownames):
        res = baseenv_ri["rownames<-"](self, conversion.py2ri(rownames))
        self.__sexp__ = res.__sexp__

    rownames = property(_get_rownames, _set_rownames, None, "Row names")

    def _get_colnames(self):
        res = baseenv_ri["colnames"](self)
        return conversion.ri2py(res)

    def _set_colnames(self, colnames):
        res = baseenv_ri["colnames<-"](self, conversion.py2ri(colnames))
        self.__sexp__ = res.__sexp__

    colnames = property(_get_colnames, _set_colnames, None)

    def cbind(self, *args, **kwargs):
        """ bind objects as supplementary columns """
        new_args = [
            self,
        ] + [conversion.ri2py(x) for x in args]
        new_kwargs = dict([(k, conversion.ri2py(v))
                           for k, v in kwargs.iteritems()])
        res = self._cbind(*new_args, **new_kwargs)
        return conversion.ri2py(res)

    def rbind(self, *args, **kwargs):
        """ bind objects as supplementary rows """
        new_args = [conversion.ri2py(x) for x in args]
        new_kwargs = dict([(k, conversion.ri2py(v))
                           for k, v in kwargs.iteritems()])
        res = self._rbind(self, *new_args, **new_kwargs)
        return conversion.ri2py(res)

    @staticmethod
    def from_csvfile(path,
                     header=True,
                     sep=",",
                     quote="\"",
                     dec=".",
                     row_names=rinterface.MissingArg,
                     col_names=rinterface.MissingArg,
                     fill=True,
                     comment_char="",
                     as_is=False):
        """ Create an instance from data in a .csv file. """
        path = conversion.py2ro(path)
        header = conversion.py2ro(header)
        sep = conversion.py2ro(sep)
        quote = conversion.py2ro(quote)
        dec = conversion.py2ro(dec)
        if row_names is not rinterface.MissingArg:
            row_names = conversion.py2ro(row_names)
        if col_names is not rinterface.MissingArg:
            col_names = conversion.py2ro(col_names)
        fill = conversion.py2ro(fill)
        comment_char = conversion.py2ro(comment_char)
        as_is = conversion.py2ro(as_is)
        res = DataFrame._read_csv(
            path, **{
                'header': header,
                'sep': sep,
                'quote': quote,
                'dec': dec,
                'row.names': row_names,
                'col.names': col_names,
                'fill': fill,
                'comment.char': comment_char,
                'as.is': as_is
            })
        res = conversion.ri2py(res)
        return res

    def to_csvfile(self,
                   path,
                   quote=True,
                   sep=",",
                   eol=os.linesep,
                   na="NA",
                   dec=".",
                   row_names=True,
                   col_names=True,
                   qmethod="escape",
                   append=False):
        """ Save the data into a .csv file. """
        path = conversion.py2ro(path)
        append = conversion.py2ro(append)
        sep = conversion.py2ro(sep)
        eol = conversion.py2ro(eol)
        na = conversion.py2ro(na)
        dec = conversion.py2ro(dec)
        row_names = conversion.py2ro(row_names)
        col_names = conversion.py2ro(col_names)
        qmethod = conversion.py2ro(qmethod)
        res = self._write_table(
            self, **{
                'file': path,
                'quote': quote,
                'sep': sep,
                'eol': eol,
                'na': na,
                'dec': dec,
                'row.names': row_names,
                'col.names': col_names,
                'qmethod': qmethod,
                'append': append
            })
        return res

    def iter_row(self):
        """ iterator across rows """
        for i in xrange(self.nrow):
            yield self.rx(i + 1, rinterface.MissingArg)

    def iter_column(self):
        """ iterator across columns """
        for i in xrange(self.ncol):
            yield self.rx(rinterface.MissingArg, i + 1)
Пример #7
0
 def __init__(self, obj):
     obj = rinterface.StrSexpVector(obj)
     super(StrVector, self).__init__(obj)
Пример #8
0
from rpy3.robjects.robject import RObjectMixin, RObject
import rpy3.rinterface as rinterface
#import rpy2.robjects.conversion as conversion
import conversion

import rpy3.rlike.container as rlc

import copy, os, itertools, time

globalenv_ri = rinterface.globalenv
baseenv_ri = rinterface.baseenv
utils_ri = rinterface.baseenv['as.environment'](rinterface.StrSexpVector(
    ("package:utils", )))


class ExtractDelegator(object):
    """ Delegate the R 'extraction' ("[") and 'replacement' ("[<-")
    of items in a vector
    or vector-like object. This can help making syntactic
    niceties possible."""

    _extractfunction = rinterface.baseenv['[']
    _replacefunction = rinterface.baseenv['[<-']

    def __init__(self, parent):
        self._parent = parent

    def __call__(self, *args, **kwargs):
        """ Subset the "R-way.", using R's "[" function. 
           In a nutshell, R indexing differs from Python indexing on:
Пример #9
0
from rpy3.robjects.methods import RS4
from rpy3.robjects.vectors import *
from rpy3.robjects.functions import Function, SignatureTranslatedFunction

from rpy3.rinterface import NA_Real, NA_Integer, NA_Logical, NA_Character

_parse = rinterface.baseenv['parse']
_reval = rinterface.baseenv['eval']
# missing values
# keep them in vectors to keep compatibility with the 2.1.x series
NA_real = FloatVector((NA_Real, ))
NA_integer = IntVector((NA_Integer, ))
NA_bool = BoolVector((NA_Logical, ))
NA_character = StrVector((NA_Character, ))
NA_complex = ComplexVector(
    _reval(_parse(text=rinterface.StrSexpVector(("NA_complex_", )))))

# NULL
NULL = _reval(_parse(text=rinterface.StrSexpVector(("NULL", ))))
# TRUE/FALSE
TRUE = _reval(_parse(text=rinterface.StrSexpVector(("TRUE", ))))
FALSE = _reval(_parse(text=rinterface.StrSexpVector(("FALSE", ))))

#FIXME: close everything when leaving (check RPy for that).


def default_ri2py(o):
    """ Convert :class:`rpy2.rinterface.Sexp` to higher-level objects,
    without copying the R objects.

    :param o: object
Пример #10
0
from rpy3.robjects.robject import RObjectMixin, RObject
import rpy3.rinterface as rinterface
#import rpy2.robjects.conversion as conversion
import conversion

baseenv_ri = rinterface.baseenv

#needed to avoid circular imports
_parse = rinterface.baseenv['parse']
_reval = rinterface.baseenv['eval']
NULL = _reval(_parse(text=rinterface.StrSexpVector(("NULL", ))))


class Function(RObjectMixin, rinterface.SexpClosure):
    """ Python representation of an R function.
    """

    __formals = baseenv_ri.get('formals')
    __local = baseenv_ri.get('local')
    __call = baseenv_ri.get('call')
    __assymbol = baseenv_ri.get('as.symbol')
    __newenv = baseenv_ri.get('new.env')

    _local_env = None

    def __init__(self, *args, **kwargs):
        super(Function, self).__init__(*args, **kwargs)
        self._local_env = self.__newenv(
            hash=rinterface.BoolSexpVector((True, )))

    def __call__(self, *args, **kwargs):