示例#1
0
 def __getitem__(self, i):
     if isinstance(i, slice):
         indices = i.indices(len(self))
         r = []
         for x in range(*indices):
             #print x
             res = super(RVector, self).__getitem__(x)
             if isinstance(res, rinterface.Sexp):
                 r.append(conversion.ri2py(res))
         return res
     else:
         res = super(RVector, self).__getitem__(i)
         if isinstance(res, rinterface.Sexp):
             res = conversion.ri2py(res)
         return res
示例#2
0
    def colnames(self):
        """ Column names

        :rtype: SexpVector
        """
        res = baseNameSpaceEnv["colnames"](self)
        return conversion.ri2py(res)
示例#3
0
 def rownames(self):
     """ Row names
     
     :rtype: SexpVector
     """
     res = baseNameSpaceEnv["rownames"](self)
     return conversion.ri2py(res)
示例#4
0
 def __fill_rpy2r__(self):
     """ Fill the attribute _rpy2r """
     name = self.__rname__
     for rname in self._env:
         if rname in self._translation:
             rpyname = self._translation[rname]
         else:
             dot_i = rname.find('.')
             if dot_i > -1:
                 rpyname = rname.replace('.', '_')
                 if rpyname in self._rpy2r:
                     raise LibraryError(('Conflict in converting R symbol'+\
                                         ' to a Python symbol ' +\
                                         '(%s -> %s while there is already'+\
                                         ' %s)') %(rname, rpyname,
                                                   rpyname))
             else:
                 rpyname = rname
             if rpyname in self.__dict__ or rpyname == '__dict__':
                 raise LibraryError('The symbol ' + rname +\
                                    ' in the package ' + name + \
                                    ' is conflicting with ' +\
                                    'a Python object attribute')
         self._rpy2r[rpyname] = rname
         rpyobj = conversion.ri2py(self._env[rname])
         rpyobj.__rname__ = rname
         #FIXME: shouldn't the original R name be also in the __dict__ ?
         self.__dict__[rpyname] = rpyobj
示例#5
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(RFunction, self).__call__(*new_args, **new_kwargs)
        res = conversion.ri2py(res)
        return res
示例#6
0
 def get(self, item, wantFun = False):
     """ Get a object from its R name/symol
     :param item: string (name/symbol)
     :param wantFun: boolean (fetch preferably a function or not)
     :rtype: object (as returned by :func:`conversion.ri2py`)
     """
     res = super(REnvironment, self).get(item, wantFun = wantFun)
     res = conversion.ri2py(res)
     return res
示例#7
0
 def assign(self, index, value):
     """ Assign a given value to a given index position in the vector """
     if not (isinstance(index, rlc.TaggedList) | \
                 isinstance(index, rlc.ArgsDict)):
         args = rlc.TaggedList([conversion.py2ro(index), ])
     else:
         for i in xrange(len(index)):
             index[i] = conversion.py2ro(index[i])
         args = index
     args.append(conversion.py2ro(value))
     args.insert(0, self)
     res = r["[<-"].rcall(args.items())
     res = conversion.ri2py(res)
     return res
示例#8
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
    (wichi means data copying).

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

    """
    if isinstance(o, RObject):
        res = rinterface.Sexp(o)
    if isinstance(o, rinterface.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):
        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
示例#9
0
    def __getitem__(self, item):
        res = rinterface.globalEnv.get(item)
            
	res = conversion.ri2py(res)
        return res
示例#10
0
 def getenvironment(self):
     """ Get the environment in which the formula is finding its symbols."""
     res = self.do_slot(".Environment")
     res = conversion.ri2py(res)
     return res
示例#11
0
 def __getattr__(self, attr):
     res = self.do_slot(attr)
     res = conversion.ri2py(res)
     return res
示例#12
0
 def __getitem__(self, item):
     res = super(REnvironment, self).__getitem__(item)
     res = conversion.ri2py(res)
     return res
示例#13
0
 def getdim(self):
     res = r.dim(self)
     res = conversion.ri2py(res)
     return res
示例#14
0
    def __getitem__(self, item):
        res = rinterface.globalEnv.get(item)
            
	res = conversion.ri2py(res)
        return res

    #FIXME: check that this is properly working
    def __cleanup__(self):
        rinterface.endEmbeddedR()
        del(self)

    def __str__(self):
        s = super(R, self).__str__()
        s += os.linesep
        version = self["version"]
        tmp = [n+': '+val[0] for n, val in itertools.izip(version.getnames(), version)]
        s += str.join(os.linesep, tmp)
        return s

    def __call__(self, string):
        p = self.parse(text=string)
        res = self.eval(p)
        return res

r = R()

globalEnv = conversion.ri2py(rinterface.globalEnv)
baseNameSpaceEnv = conversion.ri2py(rinterface.baseNameSpaceEnv)
emptyEnv = conversion.ri2py(rinterface.emptyEnv)
示例#15
0
    if not ok:
        raise LibraryError("The R package %s could not be imported" %name)
    env = _as_env(rinterface.StrSexpVector(['package:'+name, ]))
    if signature_translation:
        pack = SignatureTranslatedPackage(env, name, 
                                          translation = robject_translations)
    else:
        pack = Package(env, name, translation = robject_translations)
        
    return pack


def wherefrom(symbol, startenv = rinterface.globalenv):
    """ For a given symbol, return the environment
    this symbol is first found in, starting from 'startenv'
    """
    env = startenv
    obj = None
    tryagain = True
    while tryagain:
        try:
            obj = env[symbol]
            tryagain = False
        except LookupError, knf:
            env = env.enclos()
            if env.rsame(rinterface.emptyenv):
                tryagain = False
            else:
                tryagain = True
    return conversion.ri2py(env)