def testRS4_TypeAccessors(self): robjects.r['setClass']("R_A", robjects.r('list(foo="numeric")')) robjects.r['setMethod']("length", signature="R_A", definition = robjects.r("function(x) 123")) class R_A(methods.RS4): __metaclass__ = methods.RS4_Type __slots__ = ('get_length', 'length') __accessors__ = (('length', None, 'get_length', False, 'get the length'), ('length', None, None, True, 'length')) def __init__(self): obj = robjects.r['new']('R_A') self.__sexp__ = obj.__sexp__ class A(R_A): __rname__ = 'R_A' ra = R_A() self.assertEquals(123, ra.get_length()[0]) self.assertEquals(123, ra.length[0]) a = A() self.assertEquals(123, a.get_length()[0]) self.assertEquals(123, a.length[0])
def testMapperR2Python_s4(self): robjects.r('setClass("A", representation(x="integer"))') classname = rinterface.StrSexpVector(["A", ]) one = rinterface.IntSexpVector([1, ]) sexp = rinterface.globalenv.get("new")(classname, x=one) self.assertTrue(isinstance(robjects.default_ri2py(sexp), robjects.RS4))
def testNewFromRObject(self): numbers = robjects.r("1:5") self.assertRaises(ValueError, robjects.DataFrame, numbers) rlist = robjects.r("list(a=1, b=2, c=3)") self.assertRaises(ValueError, robjects.DataFrame, rlist) rdataf = robjects.r('data.frame(a=1:2, b=c("a", "b"))') dataf = robjects.DataFrame(rdataf)
def testSet_accessors(self): robjects.r['setClass']("A", robjects.r('list(foo="numeric")')) robjects.r['setMethod']("length", signature="A", definition = robjects.r("function(x) 123")) class A(methods.RS4): def __init__(self): obj = robjects.r['new']('A') self.__sexp__ = obj.__sexp__ acs = (('length', None, True, None), ) methods.set_accessors(A, "A", None, acs) a = A() self.assertEquals(123, a.length[0])
def testRclass_set(self): x = robjects.r("1:3") old_class = x.rclass x.rclass = robjects.StrVector(("Foo", )) + x.rclass self.assertEquals("Foo", x.rclass[0]) self.assertEquals(old_class[0], x.rclass[1])
def testNew(self): letters = robjects.r.letters numbers = robjects.r('1:26') df = robjects.RDataFrame(rlc.TaggedList((letters, numbers), tags = ('letters', 'numbers'))) self.assertEquals("data.frame", df.rclass[0])
def testRS4_TypeNoAccessors(self): robjects.r['setClass']("Foo", robjects.r('list(foo="numeric")')) class Foo(methods.RS4): __metaclass__ = methods.RS4_Type def __init__(self): obj = robjects.r['new']('R_A') self.__sexp__ = obj.__sexp__ f = Foo()
def testNewWithDotConflict(self): env = robjects.Environment() env['__dict__'] = robjects.StrVector('abcd') env['a_a'] = robjects.IntVector((1,2,3)) env['c'] = robjects.r(''' function(x) x^2''') self.assertRaises(packages.LibraryError, robjects.packages.Package, env, "dummy_package")
def testDim(self): letters = robjects.r.letters numbers = robjects.r('1:26') df = robjects.RDataFrame(rlc.TaggedList((letters, numbers), tags = ('letters', 'numbers'))) self.assertEquals(26, df.nrow()) self.assertEquals(2, df.ncol())
def testNew(self): env = robjects.Environment() env['a'] = robjects.StrVector('abcd') env['b'] = robjects.IntVector((1,2,3)) env['c'] = robjects.r(''' function(x) x^2''') pck = robjects.packages.Package(env, "dummy_package") self.assertTrue(isinstance(pck.a, robjects.Vector)) self.assertTrue(isinstance(pck.b, robjects.Vector)) self.assertTrue(isinstance(pck.c, robjects.Function))
def testFormals(self): ri_f = robjects.r('function(x, y) TRUE') res = ri_f.formals() #FIXME: no need for as.list when paired list are handled res = robjects.r['as.list'](res) self.assertEquals(2, len(res)) n = res.names self.assertEquals("x", n[0]) self.assertEquals("y", n[1])
def tearDown(self): robjects.r('setClass("A")')
def testSlotNames(self): ainstance = robjects.r('new("A", a=1, b="c")') self.assertEquals(('a', 'b'), tuple(ainstance.slotnames()))
def testEval(self): # vector long enough to span across more than one line x = robjects.baseenv['seq'](1, 50, 2) res = robjects.r('sum(%s)' %x.r_repr()) self.assertEquals(625, res[0])
def testRownames(self): dataf = robjects.r('data.frame(a=1:2, b=I(c("a", "b")))') self.assertEquals("a", dataf.colnames[0]) self.assertEquals("b", dataf.colnames[1])
def setUp(self): robjects.r('setClass("A", representation(a="numeric", b="character"))')
def testIter_col(self): dataf = robjects.r('data.frame(a=1:2, b=I(c("a", "b")))') col_types = [x.typeof for x in dataf.iter_column()] self.assertEquals(rinterface.INTSXP, col_types[0]) self.assertEquals(rinterface.STRSXP, col_types[1])
def testDim(self): letters = robjects.r.letters numbers = robjects.r("1:26") df = robjects.DataFrame(rlc.TaggedList((letters, numbers), tags=("letters", "numbers"))) self.assertEquals(26, df.nrow) self.assertEquals(2, df.ncol)
def testIsClass(self): ainstance = robjects.r('new("A", a=1, b="c")') self.assertFalse(ainstance.isclass("B")) self.assertTrue(ainstance.isclass("A"))
def testNewFromTaggedList(self): letters = robjects.r.letters numbers = robjects.r("1:26") df = robjects.DataFrame(rlc.TaggedList((letters, numbers), tags=("letters", "numbers"))) self.assertEquals("data.frame", df.rclass[0])
def Rcommand(query, silent=False, wantType='convert', listOfLists=False): unlocked = mutex.tryLock() if not unlocked: mb = QMessageBox( _("R Session Locked"), _("The R Session is currently locked, please wait for the prior execution to finish." ), QMessageBox.Information, QMessageBox.Ok | QMessageBox.Default, QMessageBox.NoButton, QMessageBox.NoButton, qApp.canvasDlg) mb.exec_() return output = None if not silent: redRLog.log(redRLog.R, redRLog.DEBUG, redRLog.getSafeString(query)) #####################Forked verions of R############################## # try: # output = qApp.R.R(query) # except Exception as inst: # print inst # x, y = inst # print showException #self.status.setText('Error occured!!') # mutex.unlock() # raise qApp.rpy.RPyRException(unicode(y)) # return None # now processes can catch potential errors #####################Forked verions of R############################## try: output = rpy.r(unicode(query).encode('Latin-1')) except Exception as inst: redRLog.log( redRLog.R, redRLog.CRITICAL, _("Error occured in the R session.\nThe orriginal query was %s.\nThe error is %s." ) % (query, inst)) mutex.unlock() raise RuntimeError( unicode(inst) + ' Orriginal Query was: ' + unicode(query)) return None # now processes can catch potential errors if wantType == 'NoConversion': mutex.unlock() return output # elif wantType == 'list': # co.setWantType(1) # elif wantType == 'dict': # co.setWantType(2) # print output.getrclass() output = convertToPy(output) # print 'converted', type(output) if wantType == None: mutex.unlock() raise Exception(_('WantType not specified')) if type(output) == list and len(output) == 1 and wantType != 'list': output = output[0] elif wantType == 'list': if type(output) is list: pass elif type(output) in [str, int, float, bool]: output = [output] elif type(output) is dict: newOutput = [] for name in output.keys(): nl = output[name] newOutput.append(nl) output = newOutput elif type(output) is numpy.ndarray: output = output.tolist() else: print _('Warning, conversion was not of a known type;'), unicode( type(output)) elif wantType == 'listOfLists': # print _('Converting to list of lists') if type(output) in [str, int, float, bool]: output = [[output]] elif type(output) in [dict]: newOutput = [] for name in output.keys(): nl = output[name] if type(nl) not in [list]: nl = [nl] newOutput.append(nl) output = newOutput elif type(output) in [list, numpy.ndarray]: if len(output) == 0: output = [output] elif type(output[0]) not in [list]: output = [output] else: print _('Warning, conversion was not of a known type;'), str( type(output)) mutex.unlock() return output
def testRownames_set(self): dataf = robjects.r('data.frame(a=1:2, b=I(c("a", "b")))') dataf.rownames = robjects.StrVector("de") self.assertEquals("d", dataf.rownames[0]) self.assertEquals("e", dataf.rownames[1])
def testCbind(self): dataf = robjects.r('data.frame(a=1:2, b=I(c("a", "b")))') dataf = dataf.cbind(robjects.r('data.frame(a=1:2, b=I(c("a", "b")))')) self.assertEquals(4, dataf.ncol) self.assertEquals(2, len([x for x in dataf.colnames if x == "a"]))
def testIter_row(self): dataf = robjects.r('data.frame(a=1:2, b=I(c("a", "b")))') rows = [x for x in dataf.iter_row()] self.assertEquals(1, rows[0][0][0]) self.assertEquals("b", rows[1][1][0])
def testValidObject(self): ainstance = robjects.r('new("A", a=1, b="c")') self.assertTrue(ainstance.validobject())