예제 #1
0
def rpy2py_basic(obj):    
    if hasattr(obj, '__len__'):
        if obj.typeof in [ri.INTSXP, ri.REALSXP, ri.CPLXSXP, 
                            ri.STRSXP]:
            res = [x for x in obj]
        elif obj.typeof in [ri.VECSXP]:
            res = [rpy2py(x) for x in obj]
        else:
            raise ValueError("Invalid type %i (%s) for 'obj'." %(obj.typeof, ri.str_typeint(obj.typeof)))
    else:
        res = Robj(obj)
    return res
예제 #2
0
    def __init__(self, obj, stringsasfactor=False):
        """ Create a new data frame.

        :param obj: object inheriting from rpy2.rinterface.SexpVector,
                    or inheriting from TaggedList
                    or a mapping name -> value
        :param stringsasfactors: Boolean indicating whether vectors
                    of strings should be turned to vectors. Note
                    that factors will not be turned to string vectors.
        """
        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)
                return
            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()]
        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")

        # Check if there is a conflicting column name
        if 'stringsAsFactors' in (k for k, v in kv):
            warnings.warn('The column name "stringsAsFactors" is '
                          'conflicting with named parameter '
                          'in underlying R function "data.frame()".')
        else:
            kv.append(('stringsAsFactors', stringsasfactor))

        # Call R's data frame constructor
        kv = tuple(kv)
        df = baseenv_ri.get("data.frame").rcall(kv, globalenv_ri)
        super(DataFrame, self).__init__(df)
예제 #3
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)
예제 #4
0
파일: vectors.py 프로젝트: hansenrl/cs249-2
    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)
예제 #5
0
 def testStr_typeint(self):
     t = rinterface.baseenv['letters']
     self.assertEqual('STRSXP', rinterface.str_typeint(t.typeof))
     t = rinterface.baseenv['pi']
     self.assertEqual('REALSXP', rinterface.str_typeint(t.typeof))
예제 #6
0
 def testStr_typeint(self):
     t = rinterface.baseenv['letters']
     self.assertEqual('STRSXP', rinterface.str_typeint(t.typeof))
     t = rinterface.baseenv['pi']
     self.assertEqual('REALSXP', rinterface.str_typeint(t.typeof))
예제 #7
0
            input_dict = INPUT_NOT_DETERMINED_DICT.copy()
            input_dict.update({
                'name': simplify_text(formal_name),
                'label': quoteattr(formal_name),
                'help': quoteattr(str(formal_value).strip()),
                'value': '',
                'multiple': False,
            })
            input_template = optional_input_text
            use_quotes = True
            try:
                value_name, value_value = list(formal_value.items())[0]
                #print 'value_name', value_name, type(value_name)
                #print 'value_value typeof, typeof_str', value_value.typeof, str_typeint( value_value.typeof ), type(str_typeint( value_value.typeof ))  #use value_value

                r_type = str_typeint(value_value.typeof)
                if r_type == 'INTSXP':
                    input_type = 'integer'
                    default_value = str(value_value[0])
                    input_template = optional_input_integer
                    use_quotes = False
                    input_dict['integer_selected'] = True
                    input_type = 'not_determined'
                elif r_type == 'LGLSXP':  #this seems to have caught NA...FIXME
                    input_type = 'boolean'
                    default_value = str(value_value[0])
                    input_template = optional_input_boolean
                    use_quotes = False
                    if default_value == 'NULL':
                        input_dict['NULL_selected'] = True
                    elif default_value == 'NA':
예제 #8
0
 def testStr_typeint(self):
     t = rinterface.baseenv["letters"]
     self.assertEqual("STRSXP", rinterface.str_typeint(t.typeof))
     t = rinterface.baseenv["pi"]
     self.assertEqual("REALSXP", rinterface.str_typeint(t.typeof))
예제 #9
0
 def testStr_typeint_invalid(self):
     with self.assertRaises(LookupError):
         rinterface.str_typeint(99)