Ejemplo n.º 1
0
    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, 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, rlc.TaggedList):
            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)
        elif hasattr(tlist, "__iter__"):
            if not callable(tlist.__iter__):
                raise ValueError("tlist should have a /method/ __iter__ (not an attribute)")
            kv = [(str(k), conversion.py2ri(tlist[k])) for k in tlist]
            df = baseenv_ri.get("data.frame").rcall(tuple(kv), globalenv_ri)
            super(DataFrame, self).__init__(df)
        else:
            raise ValueError("tlist can be either "+
                             "an instance of an iter-able class" +
                             "(such a Python dict, rpy2.rlike.container OrdDict" +
                             " or an instance of rpy2.rinterface.SexpVector" +
                             " of type VECSXP")
Ejemplo n.º 2
0
    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, 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, rlc.TaggedList):
            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)
        elif hasattr(tlist, "__iter__"):
            if not callable(tlist.__iter__):
                raise ValueError(
                    "tlist should have a /method/ __iter__ (not an attribute)")
            kv = [(str(k), conversion.py2ri(tlist[k])) for k in tlist]
            df = baseenv_ri.get("data.frame").rcall(tuple(kv), globalenv_ri)
            super(DataFrame, self).__init__(df)
        else:
            raise ValueError(
                "tlist can be either " + "an instance of an iter-able class" +
                "(such a Python dict, rpy2.rlike.container OrdDict" +
                " or an instance of rpy2.rinterface.SexpVector" +
                " of type VECSXP")
Ejemplo n.º 3
0
 def __call__(self, *args, **kwargs):
     new_args = [conversion.py2ri(a) for a in args]
     new_kwargs = {}
     for k, v in kwargs.iteritems():
         new_kwargs[k] = conversion.py2ri(v)
     res = super(Function, self).__call__(*new_args, **new_kwargs)
     res = conversion.ri2py(res)
     return res
Ejemplo n.º 4
0
 def __call__(self, *args, **kwargs):
     new_args = [conversion.py2ri(a) for a in args]
     new_kwargs = {}
     for k, v in kwargs.iteritems():
         new_kwargs[k] = conversion.py2ri(v)
     res = super(Function, self).__call__(*new_args, **new_kwargs)
     res = conversion.ri2py(res)
     return res
Ejemplo n.º 5
0
 def __init__(self, o):
     if not isinstance(o, SexpVector):
         o = conversion.py2ri(o)
     super(Vector, self).__init__(o)
     self.ro = VectorOperationsDelegator(self)
     self.rx = ExtractDelegator(self)
     self.rx2 = DoubleExtractDelegator(self)
Ejemplo n.º 6
0
    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.")
Ejemplo n.º 7
0
def default_py2ro(o):
    """ Convert any Python object into an robject.
    :param o: object
    :rtype: :class:`rpy2.robjects.RObject (and subclasses)`
    """
    res = conversion.py2ri(o)
    return conversion.ri2py(res)
Ejemplo n.º 8
0
def default_py2ro(o):
    """ Convert any Python object into an robject.
    :param o: object
    :rtype: :class:`rpy2.robjects.RObject (and subclasses)`
    """
    res = conversion.py2ri(o)
    return conversion.ri2py(res)
Ejemplo n.º 9
0
 def __init__(self, o):
     if not isinstance(o, SexpVector):
         o = conversion.py2ri(o)
     super(Vector, self).__init__(o)
     self.ro = VectorOperationsDelegator(self)
     self.rx = ExtractDelegator(self)
     self.rx2 = DoubleExtractDelegator(self)
Ejemplo n.º 10
0
def default_py2ri(o):
    """ Convert arbitrary Python object to :class:`rpy2.rinterface.Sexp` to objects,
    creating an R object with the content of the Python object in the process
    (wich means data copying).

    :param o: object
    :rtype: :class:`rpy2.rinterface.Sexp` (and subclasses)

    """
    if isinstance(o, RObject):
        res = rinterface.Sexp(o)
    if isinstance(o, Sexp):
        res = o
    elif isinstance(o, array.array):
        if o.typecode in ('h', 'H', 'i', 'I'):
            res = rinterface.SexpVector(o, rinterface.INTSXP)
        elif o.typecode in ('f', 'd'):
            res = rinterface.SexpVector(o, rinterface.REALSXP)
        else:
            raise (ValueError(
                "Nothing can be done for this array type at the moment."))
    elif isinstance(o, bool):
        res = rinterface.SexpVector([
            o,
        ], rinterface.LGLSXP)
    elif isinstance(o, int) or isinstance(o, long):
        # special case for NA_Logical
        if o is rinterface.NA_Logical:
            res = rinterface.SexpVector([
                o,
            ], rinterface.LGLSXP)
        else:
            res = rinterface.SexpVector([
                o,
            ], rinterface.INTSXP)
    elif isinstance(o, float):
        res = rinterface.SexpVector([
            o,
        ], rinterface.REALSXP)
    elif isinstance(o, str):
        res = rinterface.SexpVector([
            o,
        ], rinterface.STRSXP)
    elif isinstance(o, unicode):
        res = rinterface.SexpVector([
            o,
        ], rinterface.STRSXP)
    elif isinstance(o, list):
        res = r.list(*[conversion.ri2py(conversion.py2ri(x)) for x in o])
    elif isinstance(o, complex):
        res = rinterface.SexpVector([
            o,
        ], rinterface.CPLXSXP)
    else:
        raise (ValueError(
            "Nothing can be done for the type %s at the moment." % (type(o))))
    return res
Ejemplo n.º 11
0
 def __init__(self, tlist):
     if isinstance(tlist, rinterface.SexpVector):
         if tlist.typeof != rinterface.VECSXP:
             raise ValueError("tlist should of typeof VECSXP")
         super(ListVector, self).__init__(tlist)
     elif isinstance(tlist, rlc.TaggedList):
         kv = [(k, conversion.py2ri(v)) for k,v in tlist.iteritems()]
         kv = tuple(kv)
         df = baseenv_ri.get("list").rcall(kv, globalenv_ri)
         super(ListVector, self).__init__(df)
     elif hasattr(tlist, "__iter__"):
         if not callable(tlist.__iter__):
             raise ValueError("tlist should have a /method/ __iter__ (not an attribute)")
         kv = [(str(k), conversion.py2ri(tlist[k])) for k in tlist]
         kv = tuple(kv)
         df = baseenv_ri.get("list").rcall(kv, globalenv_ri)
         super(ListVector, self).__init__(df)
     else:
         raise ValueError("tlist can be either "+
                          "an iter-able " +
                          " or an instance of rpy2.rinterface.SexpVector" +
                          " of type VECSXP, or a Python dict.")
Ejemplo n.º 12
0
 def __init__(self, tlist):
     if isinstance(tlist, rinterface.SexpVector):
         if tlist.typeof != rinterface.VECSXP:
             raise ValueError("tlist should of typeof VECSXP")
         super(ListVector, self).__init__(tlist)
     elif isinstance(tlist, rlc.TaggedList):
         kv = [(k, conversion.py2ri(v)) for k, v in tlist.iteritems()]
         kv = tuple(kv)
         df = baseenv_ri.get("list").rcall(kv, globalenv_ri)
         super(ListVector, self).__init__(df)
     elif hasattr(tlist, "__iter__"):
         if not callable(tlist.__iter__):
             raise ValueError(
                 "tlist should have a /method/ __iter__ (not an attribute)")
         kv = [(str(k), conversion.py2ri(tlist[k])) for k in tlist]
         kv = tuple(kv)
         df = baseenv_ri.get("list").rcall(kv, globalenv_ri)
         super(ListVector, self).__init__(df)
     else:
         raise ValueError("tlist can be either " + "an iter-able " +
                          " or an instance of rpy2.rinterface.SexpVector" +
                          " of type VECSXP, or a Python dict.")
Ejemplo n.º 13
0
    def __init__(self, obj):
        """ Create a new data frame.

        :param obj: object inheriting from rpy2.rinterface.SexpVector,
                    or inheriting from TaggedList
                    or a mapping name -> value
        """
        if isinstance(obj, rinterface.SexpVector):
            if obj.typeof != rinterface.VECSXP:
                raise ValueError("obj should of typeof VECSXP"+\
                                     " (and we get %s)" % rinterface.str_typeint(obj.typeof))
            if self._is_list(obj)[0] or \
                    globalenv_ri.get('inherits')(obj, self._dataframe_name)[0]:
                #FIXME: is it really a good idea to pass R lists
                # to the constructor ?
                super(DataFrame, self).__init__(obj)
            else:
                raise ValueError(
            "When passing R objects to build a DataFrame," +\
                " the R object must be a list or inherit from" +\
                " the R class 'data.frame'")
        elif isinstance(obj, rlc.TaggedList):
            kv = [(k, conversion.py2ri(v)) for k,v in obj.items()]
            kv = tuple(kv)
            df = baseenv_ri.get("data.frame").rcall(kv, globalenv_ri)
            super(DataFrame, self).__init__(df)
        else:
            try:
                kv = [(str(k), conversion.py2ri(obj[k])) for k in obj]
            except TypeError:
                raise ValueError("obj can be either "+
                                 "an instance of an iter-able class" +
                                 "(such a Python dict, rpy2.rlike.container OrdDict" +
                                 " or an instance of rpy2.rinterface.SexpVector" +
                                 " of type VECSXP")
            
            df = baseenv_ri.get("data.frame").rcall(tuple(kv), globalenv_ri)
            super(DataFrame, self).__init__(df)
Ejemplo n.º 14
0
def default_py2ri(o):
    """ Convert arbitrary Python object to :class:`rpy2.rinterface.Sexp` to objects,
    creating an R object with the content of the Python object in the process
    (wich means data copying).

    :param o: object
    :rtype: :class:`rpy2.rinterface.Sexp` (and subclasses)

    """
    if isinstance(o, RObject):
        res = rinterface.Sexp(o)
    if isinstance(o, Sexp):
        res = o
    elif isinstance(o, array.array):
        if o.typecode in ('h', 'H', 'i', 'I'):
            res = rinterface.SexpVector(o, rinterface.INTSXP)
        elif o.typecode in ('f', 'd'):
            res = rinterface.SexpVector(o, rinterface.REALSXP)
        else:
            raise(ValueError("Nothing can be done for this array type at the moment."))
    elif isinstance(o, bool):
        res = rinterface.SexpVector([o, ], rinterface.LGLSXP)
    elif isinstance(o, int) or isinstance(o, long):
        # special case for NA_Logical
        if o is rinterface.NA_Logical:
            res = rinterface.SexpVector([o, ], rinterface.LGLSXP)
        else:
            res = rinterface.SexpVector([o, ], rinterface.INTSXP)
    elif isinstance(o, float):
        res = rinterface.SexpVector([o, ], rinterface.REALSXP)
    elif isinstance(o, str):
        res = rinterface.SexpVector([o, ], rinterface.STRSXP)
    elif isinstance(o, unicode):
        res = rinterface.SexpVector([o, ], rinterface.STRSXP)
    elif isinstance(o, list):
        res = r.list(*[conversion.ri2py(conversion.py2ri(x)) for x in o])
    elif isinstance(o, complex):
        res = rinterface.SexpVector([o, ], rinterface.CPLXSXP)
    else:
        raise(ValueError("Nothing can be done for the type %s at the moment." %(type(o))))
    return res
Ejemplo n.º 15
0
    def __init__(self, tlist):
        """ Create a new data frame.

        :param tlist: rpy3.rlike.container.TaggedList or rpy3.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 rpy3.rlike.container.TaggedList," +
                             " or an instance of rpy3.rinterface.SexpVector" +
                             " of type VECSXP, or a Python dict.")
Ejemplo n.º 16
0
 def __ge__(self, x):
     res = globalenv_ri.get(">=")(self._parent, conversion.py2ri(x))
     return conversion.ri2py(res)
Ejemplo n.º 17
0
 def __ge__(self, x):
     res = globalenv_ri.get(">=")(self._parent, conversion.py2ri(x))
     return conversion.ri2py(res)
Ejemplo n.º 18
0
 def __add__(self, x):
     res = baseenv_ri.get("c")(self, conversion.py2ri(x))
     res = conversion.ri2py(res)
     return res
Ejemplo n.º 19
0
 def __setitem__(self, i, value):
     value = conversion.py2ri(value)
     res = super(Vector, self).__setitem__(i, value)
Ejemplo n.º 20
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,
                                       complete = complete)[0]
Ejemplo n.º 21
0
 def __add__(self, x):
     res = baseenv_ri.get("c")(self, conversion.py2ri(x))
     res = conversion.ri2py(res)
     return res
Ejemplo n.º 22
0
 def __setitem__(self, i, value):
     value = conversion.py2ri(value)
     res = super(Vector, self).__setitem__(i, value)
Ejemplo n.º 23
0
 def _set_rownames(self, rownames):
     res = baseenv_ri["rownames<-"](self, conversion.py2ri(rownames))
     self.__sexp__ = res.__sexp__
Ejemplo n.º 24
0
 def isclass(name):
     """ Return whether the given name is a defined class. """
     name = conversion.py2ri(name)
     return methods_env['isClass'](name)[0]
Ejemplo n.º 25
0
 def isclass(name):
     """ Return whether the given name is a defined class. """
     name = conversion.py2ri(name)
     return methods_env['isClass'](name)[0]
Ejemplo n.º 26
0
 def _set_colnames(self, colnames):
     res = baseenv_ri["colnames<-"](self, conversion.py2ri(colnames))
     self.__sexp__ = res.__sexp__
Ejemplo n.º 27
0
 def _set_rownames(self, rownames):
     res = baseenv_ri["rownames<-"](self, conversion.py2ri(rownames))
     self.__sexp__ = res.__sexp__
Ejemplo n.º 28
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,
                                       complete=complete)[0]
Ejemplo n.º 29
0
 def _set_colnames(self, colnames):
     res = baseenv_ri["colnames<-"](self, conversion.py2ri(colnames))
     self.__sexp__ = res.__sexp__