Example #1
0
    def sendMe(self):
        xCol = unicode(self.xColumnSelector.currentText())
        yCol = unicode(self.yColumnSelector.currentText())

        xData = self.R('as.numeric(' + self.data + '[,"' + unicode(xCol) +
                       '"])',
                       wantType='list')
        yData = self.R('as.numeric(' + self.data + '[,"' + unicode(yCol) +
                       '"])',
                       wantType='list')

        selected, unselected = self.graph.getSelectedPoints(xData=xData,
                                                            yData=yData)
        # print selected
        # print unselected
        index = []
        for x in selected:
            if x == 1: index.append('T')
            else: index.append('F')

        index = 'c(' + ','.join(index) + ')'
        self.R('%s<-%s[%s,]' % (self.Rvariables['selected'], self.data, index),
               silent=True)
        if self.dataParent:
            data = redRRDataFrame(data=self.Rvariables['selected'],
                                  parent=self.dataParent.getDataParent())
            data.copyAllOptionalData(self.dataParent)
        else:
            data = redRRDataFrame(data=self.Rvariables['selected'])
        self.rSend("id0", data)
Example #2
0
    def subset(
        self
    ):  # now we need to make the R command that will handle the subsetting.
        if self.data == None or self.data == '':
            self.status.setText(_("Connect data before processing"))
            return

        selectedDFItems = []
        for name in self.attributes.selectedItems():
            selectedDFItems.append('"' + unicode(name.text()) +
                                   '"')  # get the text of the selected items

        if self.rowcolBox.getChecked() == _('Row'):
            if _("Selected") in self.sendSection.getChecked():
                self.R(self.Rvariables['rowcolSelector'] + '<-as.data.frame(' +
                       self.data + '[rownames(' + self.data + ')' +
                       ' %in% c(' + ','.join(selectedDFItems) + ')' +
                       ',,drop = FALSE])',
                       wantType='NoConversion')
                newData = redRRDataFrame(
                    data=self.Rvariables['rowcolSelector'])
                self.rSend('id0', newData)
            else:
                self.rSend('id0', None)
            if _("Not Selected") in self.sendSection.getChecked():
                self.R(self.Rvariables['rowcolSelectorNot'] +
                       '<-as.data.frame(' + self.data + '[!rownames(' +
                       self.data + ') %in% c(' + ','.join(selectedDFItems) +
                       '),,drop = FALSE])',
                       wantType='NoConversion')
                newDataNot = redRRDataFrame(
                    data=self.Rvariables['rowcolSelectorNot'])
                self.rSend('id1', newDataNot)
            else:
                self.rSend('id1', None)
        elif self.rowcolBox.getChecked() == _('Column'):
            if _("Selected") in self.sendSection.getChecked():
                self.R(self.Rvariables['rowcolSelector'] + '<-as.data.frame(' +
                       self.data + '[,colnames(' + self.data + ')' +
                       ' %in% c(' + ','.join(selectedDFItems) + ')' +
                       ',drop = FALSE])',
                       wantType='NoConversion')
                newData = redRRDataFrame(
                    data=self.Rvariables['rowcolSelector'])
                self.rSend('id0', newData)
            else:
                self.rSend('id0', None)
            if _("Not Selected") in self.sendSection.getChecked():
                self.R(self.Rvariables['rowcolSelectorNot'] +
                       '<-as.data.frame(' + self.data + '[,!colnames(' +
                       self.data + ')' + ' %in% c(' +
                       ','.join(selectedDFItems) + '),drop = FALSE])',
                       wantType='NoConversion')
                newDataNot = redRRDataFrame(
                    data=self.Rvariables['rowcolSelectorNot'])
                self.rSend('id1', newDataNot)
            else:
                self.rSend('id1', None)
        self.SubsetByAttached = 0
Example #3
0
    def commitFunction(self):
        if unicode(self.RFunctionParam_x) == '': return
        if self.sortingColumn1.currentText() =='':
            return
        injection = []

        injection.append('%s$%s' % (self.RFunctionParam_x, self.sortingColumn1.currentText()))
        if self.sortingColumn2.currentText() !='':
            injection.append('%s$%s' % (self.RFunctionParam_x, self.sortingColumn2.currentText()))
        if self.sortingColumn3.currentText() !='':
            injection.append('%s$%s' % (self.RFunctionParam_x, self.sortingColumn3.currentText()))
            
            
        if _('Decreasing') in self.options.getChecked():
            string = 'decreasing=TRUE'
            injection.append(string)
        else:
            injection.append('decreasing = FALSE')
        if _('NA Last') in self.options.getChecked():
            injection.append('na.last = TRUE')
        inj = ','.join(injection)

        self.R(self.Rvariables['sort']+'<-%s[order(%s),]' % (self.RFunctionParam_x, inj), wantType = 'NoConversion')
        newData = redRRDataFrame(data = self.Rvariables["sort"]) 
        
        self.rSend("id0", newData)
Example #4
0
 def commitFunction(self):
     if not self.require_librarys(['reshape']):
         self.status.setText(_('R Libraries Not Loaded.'))
         return
     if self.RFunctionParam_na_rm == 0: pna = 'TRUE'
     else: pna = 'FALSE'
     if self.RFunctionParam_data == '': return
     mvItem = self.RFunctionParam_measure_var.selectedItems()
     try:
         mvStr = []
         for item in mvItem:
             mvStr.append(unicode(item.text()))
         mvStr = ', measure.var = c(\''+'\',\''.join(mvStr)+'\')'
         if mvStr == ', measure.var = c(\'\')':
             mvStr = ''
     except:
         mvStr = ''
     ivItem = self.RFunctionParam_id_var.selectedItems()
     try:
         ivStr = []
         for item in ivItem:
             ivStr.append(unicode(ivItem.text()))
         ivStr = ', id.var = c(\''+'\',\''.join(ivStr)+'\')'
         if ivStr == ', id.var = c(\'\')': ivStr = ''
     except:
         ivStr = ''
     self.R('OldRownames<-rownames('+unicode(self.RFunctionParam_data)+')', wantType = 'NoConversion')
     self.R(self.Rvariables['melt.data.frame']+'<-melt.data.frame(data=cbind('+unicode(self.RFunctionParam_data)+', OldRownames),na.rm='+unicode(pna)+mvStr+',variable.name="'+unicode(self.RFunctionParam_variable_name.text())+'"'+ivStr+')', wantType = 'NoConversion')
     self.R('rm(OldRownames)', wantType = 'NoConversion')
     # copy the signals class and send the newData
     newData = redRRDataFrame(data = self.Rvariables['melt.data.frame'])
     newData.dictAttrs = self.data.dictAttrs.copy()
     self.rSend("id0", newData)
     
Example #5
0
 def sendThis(self):
     if unicode(self.command.textCursor().selectedText()) != '':
         text = unicode(self.command.textCursor().selectedText())
     else:
         self.sendStatus.setText(_('No object Selected'))
         return
     thisdataclass = self.R('class(' + unicode(text) + ')')
     thisdata = unicode(text)
     # use upclassing to convert to signals class
     if thisdataclass.__class__.__name__ == 'list':  #this is a special R type so just send as generic
         newData = redRRVariable(data=unicode(text))
         self.rSend("id3", newData)
     elif thisdataclass.__class__.__name__ == 'str':
         if thisdataclass in ['numeric', 'character', 'logical'
                              ]:  # we have a numeric vector as the object
             newData = redRRVector(data=unicode(text))
             self.rSend("id2", newData)
             self.sendStatus.setText(
                 thisdata + _(' sent through the R Vector channel'))
         elif thisdataclass in ['data.frame']:
             newData = redRRDataFrame(data=unicode(text))
             self.rSend("id0", newData)
             self.sendStatus.setText(
                 thisdata + _(' sent through the R Data Frame channel'))
         elif thisdataclass in ['matrix']:
             newData = redRRMatrix(data=unicode(text))
             self.rSend("id4", newData)
             self.sendStatus.setText(thisdata +
                                     _(' sent through the Matrix channel'))
         elif thisdataclass == 'list':  # the object is a list
             for i in range(self.R('length(' + text + ')')):
                 if self.R('class(%s[[%s]])' % (text, i),
                           silent=True) not in [
                               'numeric', 'character', 'real', 'complex',
                               'factor'
                           ]:
                     newData = ral.RArbitraryList(data=self.sendThis)
                     self.status.setText(
                         _('Data sent through the R Arbitrary List channel')
                     )
                     self.rSend('ral', newData)
                     return
             newData = redRRList(data=unicode(text))
             self.rSend("id1", newData)
             self.sendStatus.setText(thisdata +
                                     _(' sent through the R List channel'))
         else:  # the data is of a non-normal type send anyway as generic
             newData = redRRVariable(data=unicode(text))
             self.rSend("id3", newData)
             self.sendStatus.setText(
                 thisdata + _(' sent through the R Object channel'))
     else:
         newData = redRRVariable(data=unicode(text))
         self.rSend("id3", newData)
         self.sendStatus.setText(thisdata +
                                 ' sent through the R Object channel')
Example #6
0
    def commitFunction(self):
        if self.x == '': return

        self.R(self.Rvariables['t'] + '<-as.data.frame(t(x=' +
               unicode(self.RFunctionParam_x) + '))',
               wantType='NoConversion')

        newData = redRRDataFrame(data=self.Rvariables['t'])
        newData.dictAttrs = self.data.dictAttrs.copy()
        self.rSend("id0", newData)
Example #7
0
    def subOnAttached(self):
        if self.data == None or self.data == '': return

        col = unicode(self.subsetColumn.currentText())

        if self.rowcolBox.getChecked() == _('Row'):
            if _("Selected") in self.sendSection.getChecked():
                self.R(self.Rvariables['rowcolSelector'] + '<-as.data.frame(' +
                       self.data + '[rownames(' + self.data + ')' + ' %in% ' +
                       self.ssv + '[["' + col + '"]],,drop = FALSE])',
                       wantType='NoConversion')
                newData = redRRDataFrame(
                    data=self.Rvariables['rowcolSelector'])
                self.rSend('id0', newData)
            if _("Not Selected") in self.sendSection.getChecked():
                self.R(self.Rvariables['rowcolSelectorNot'] +
                       '<-as.data.frame(' + self.data + '[!rownames(' +
                       self.data + ')' + ' %in% ' + self.ssv + '[["' + col +
                       '"]],,drop = FALSE])',
                       wantType='NoConversion')
                newDataNot = redRRDataFrame(
                    data=self.Rvariables['rowcolSelectorNot'])
                self.rSend('id1', newDataNot)
        elif self.rowcolBox.getChecked() == 'Column':
            if _("Selected") in self.sendSection.getChecked():
                self.R(self.Rvariables['rowcolSelector'] + '<-as.data.frame(' +
                       self.data + '[,colnames(' + self.data + ')' + ' %in% ' +
                       self.ssv + '[[\'' + col + '\']],drop = FALSE])',
                       wantType='NoConversion')
                newData = redRRDataFrame(
                    data=self.Rvariables['rowcolSelector'])
                self.rSend('id0', newData)
            if _("Not Selected") in self.sendSection.getChecked():
                self.R(self.Rvariables['rowcolSelectorNot'] +
                       '<-as.data.frame(' + self.data + '[,!colnames(' +
                       self.data + ')' + ' %in% ' + self.ssv + '[[\'' + col +
                       '\']],drop = FALSE])',
                       wantType='NoConversion')
                newDataNot = redRRDataFrame(
                    data=self.Rvariables['rowcolSelectorNot'])
                self.rSend('id1', newDataNot)
        self.SubsetByAttached = 1
Example #8
0
 def commitFunction(self):
     if unicode(self.RFunctionParam_object) == '': return
     injection = []
     inj = ','.join(injection)
     self.R(self.Rvariables['na.omit'] + '<-na.omit(object=' +
            unicode(self.RFunctionParam_object) + ',' + inj + ')',
            wantType='NoConversion')
     thisdataclass = self.R('class(' + self.Rvariables['na.omit'] + ')')
     if type(thisdataclass
             ) == list:  #this is a special R type so just send as generic
         self.rSend("id3", self.data)
     elif type(thisdataclass) == str:
         if thisdataclass == 'numeric':  # we have a numeric vector as the object
             newData = redRRVector(data=self.Rvariables['na.omit'])
             newData.dictAttrs = self.data.dictAttrs.copy()
             self.rSend("id2", newData)
             self.status.setText(
                 _('Data  sent through the R Vector channel'))
         elif thisdataclass == 'character':  #we have a character vector as the object
             newData = redRRVector(data=self.Rvariables['na.omit'])
             newData.dictAttrs = self.data.dictAttrs.copy()
             self.rSend("id2", newData)
             self.status.setText(
                 _('Data  sent through the R Vector channel'))
         elif thisdataclass == 'data.frame':  # the object is a data.frame
             newData = redRRDataFrame(data=self.Rvariables['na.omit'])
             newData.dictAttrs = self.data.dictAttrs.copy()
             self.rSend("id0", newData)
             self.status.setText(
                 _('Data  sent through the R Data Frame channel'))
         elif thisdataclass == 'matrix':  # the object is a matrix
             newData = rmat.RMatrix(data=self.Rvariables['na.omit'])
             newData.dictAttrs = self.data.dictAttrs.copy()
             self.rSend("id0", newData)
             self.status.setText(
                 _('Data  sent through the R Data Frame channel'))
         elif thisdataclass == 'list':  # the object is a list
             newData = redRRList(data=self.Rvariables['na.omit'])
             newData.dictAttrs = self.data.dictAttrs.copy()
             self.rSend("id1", newData)
             self.status.setText(_('Data  sent through the R List channel'))
         else:  # the data is of a non-normal type send anyway as generic
             newData = redRRVariable(data=self.Rvariables['na.omit'])
             newData.dictAttrs = self.data.dictAttrs.copy()
             self.rSend("id3", newData)
             self.status.setText(
                 _('Data  sent through the R Object channel'))
     else:
         newData = redRRVariable(data=self.Rvariables['na.omit'])
         newData.dictAttrs = self.data.dictAttrs.copy()
         self.rSend("id3", newData)
         self.status.setText(_('Data  sent through the R Object channel'))
Example #9
0
    def sendSelection(self):
        #print self.names.selectedItems()[0]
        if self.data == None:
            self.status.setText('No data to process')
            return
        name = unicode(self.names.row(self.names.currentItem()) + 1)
        self.Rvariables['listelement'] = self.data + '[[' + name + ']]'
        # use signals converter in OWWidget to convert to the signals class
        myclass = self.R('class(' + self.Rvariables['listelement'] + ')')
        print myclass
        if myclass == 'data.frame':

            newData = redRRDataFrame(data=self.Rvariables['listelement'],
                                     parent=self.Rvariables['listelement'])
            self.rSend("id0", newData)
            #self.infoa.setText('Sent Data Frame')
            slot = 'Data Frame'
        elif myclass == 'list':
            newData = redRRList(data=self.Rvariables['listelement'])
            self.rSend("id2", newData)
            #self.infoa.setText('Sent List')
            slot = 'List'
        elif myclass in [
                'vector', 'character', 'factor', 'logical', 'numeric',
                'integer', ['POSIXt', 'POSIXct']
        ]:
            newData = redRRVector(data=self.Rvariables['listelement'])
            self.rSend("id1", newData)
            #self.infoa.setText('Sent Vector')
            slot = 'Vector'
        elif myclass in ['matrix']:
            newData = redRRMatrix(data=self.Rvariables['listelement'])
            self.rSend("id4", newData)
            #self.infoa.setText('Sent Matrix')
            slot = 'Matrix'
        else:
            newData = redRRVariable(data=self.Rvariables['listelement'])
            self.rSend("id3", newData)
            slot = 'R Variable'

        self.infoa.setText(
            _('Sent %(NAME)s as %(SLOT)s') % {
                'NAME': name,
                'SLOT': slot
            })
Example #10
0
 def commitFunction(self):
     if unicode(self.RFunctionParam_a) == '': return
     if unicode(self.RFunctionParam_b) == '': return
     injection = []
     if unicode(self.RFunctionParamdeparse_level_lineEdit.text()) != '':
         string = 'deparse.level=' + unicode(
             self.RFunctionParamdeparse_level_lineEdit.text()) + ''
         injection.append(string)
     inj = ','.join(injection)
     self.R(self.Rvariables['cbind'] + '<-cbind(' +
            unicode(self.RFunctionParam_a) + ',' +
            unicode(self.RFunctionParam_b) + ',' + inj + ')',
            wantType='NoConversion')
     newData = redRRDataFrame(
         data=self.Rvariables["cbind"]
     )  # moment of variable creation, no preexisting data set.  To pass forward the data that was received in the input uncomment the next line.
     #newData.copyAllOptinoalData(self.data)  ## note, if you plan to uncomment this please uncomment the call to set self.data in the process statemtn of the data whose attributes you plan to send forward.
     self.rSend("id0", newData)
Example #11
0
 def commitFunction(self):
     package = self.package.text()
     dataset = unicode(self.RFunctionParamdataName_lineEdit.text())
     if package == '' or dataset == '':
         return
     # the package does not need to be loaded to get its datasets
     # self.loadPackage()
     self.R('data("%s", package="%s")' % (dataset, package),
            wantType='NoConversion')
     try:
         newData = redRRDataFrame(
             data='as.data.frame(' +
             unicode(self.RFunctionParamdataName_lineEdit.text() + ')'))
         self.rSend("id0", newData)
     except RuntimeError as inst:
         QMessageBox.information(self, _('Red-R Canvas'),
                                 _('R Error: %s') % unicode(inst),
                                 QMessageBox.Ok + QMessageBox.Default)
Example #12
0
    def commitFunction(self):
        func = unicode(self.functionText.toPlainText())
        paramText = unicode(self.parameters.text())
        if unicode(self.data) == None or func == '': return

        params = []
        for x in paramText.split(','):
            if x.strip() != '':
                params.append(x.strip())

        saveAs = func
        if len(params):
            saveAs += '\n--' + '\n--'.join(params)

        if not self.functions.findItems(saveAs, Qt.MatchExactly):
            self.functions.addItem(saveAs)
            self.saveGlobalSettings()

        injection = []
        string = 'MARGIN = %s' % unicode(self.indexSpinBox.value())
        injection.append(string)

        string = 'FUN=' + unicode(self.functionText.toPlainText())
        injection.append(string)

        injection.extend(params)

        inj = ','.join(injection)

        # try:
        self.R(self.Rvariables['apply'] + '<- as.data.frame(apply(X=' +
               unicode(self.data) + ',' + inj + '))',
               wantType='NoConversion')
        self.outputTable.setRTable(self.Rvariables['apply'])
        newData = redRRDataFrame(data=self.Rvariables['apply'])
        self.rSend("id0", newData)
Example #13
0
 def sendMe(self,kill=False):
         newDataAll = redRRDataFrame(data = self.Rvariables['merged'])
         newDataAll.dictAttrs = self.dataParentB.dictAttrs.copy()
         newDataAll.dictAttrs.update(self.dataParentA.dictAttrs)
         self.rSend("id0", newDataAll)
Example #14
0
    def commitSubset(self):
        filteredData = self.table.getFilteredData()
        newData = redRRDataFrame(data = filteredData, parent = self.dataParent.getData())

        self.rSend('id0', newData)
Example #15
0
    def commitTable(self):
        #run through the table and make the output
        
        #self.dataTable.getData()
        
        trange = self.dataTable.selectedRanges()[0]
        
        #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, ','.join([str(a) for a in trange.leftColumn(), trange.rightColumn(), trange.topRow(), trange.bottomRow()]))
        if trange.leftColumn() == trange.rightColumn() and trange.topRow() == trange.bottomRow():
            rowi = range(0, self.maxRow+1)
            coli = range(0, self.maxCol+1)
        else:

            rowi = range(trange.topRow(), trange.bottomRow()+1)
            coli = range(trange.leftColumn(), trange.rightColumn()+1)
            
        if self.dataTable.item(rowi[0], coli[0]) == None: 
            #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Setting row and col headers to true')
            self.rowHeaders.setChecked(['Use Row Headers', 'Use Column Headers'])
            #self.rowHeaders.setChecked(['Use Column Headers'])
        rownames = {}
        colnames = {}
        if 'Use Row Headers' in self.rowHeaders.getChecked():
            #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Using Row headers')
            for i in rowi:
                item = self.dataTable.item(i, coli[0])
                if item != None:
                    thisText = item.text()
                else: thisText = unicode(i)
                if thisText == None or thisText == '':
                    thisText = unicode(i)
                    
                rownames[unicode(i)] = unicode(thisText)
            coli = coli[1:] #index up the cols

        if 'Use Column Headers' in self.rowHeaders.getChecked():
            #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Using col headers')
            for j in coli:
                item = self.dataTable.item(rowi[0], j)
                if item != None:
                    thisText = item.text()
                else: thisText = '"'+unicode(j)+'"'
                if thisText == None or thisText == '':
                    thisText = '"'+unicode(j)+'"'
                thisText = thisText.split(' ')[0]
                colnames[unicode(j)] = (unicode(thisText))
            #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, unicode(colnames))
            rowi = rowi[1:]
        rinsertion = []
        
        for j in coli:
            element = ''
            if colnames:
                element += colnames[unicode(j)]+'='
            if self.classes:
                element += self.classes[j-1][0]
            element += 'c('
            inserts = []
            for i in rowi:
                #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'inserting data in cell i %s, j %s' % (i, j))
                tableItem = self.dataTable.item(i,j)
                if tableItem == None:
                    inserts.append('NA')
                else:
                    try: #catch if the element can be coerced to numeric in the table
                        float(tableItem.text()) #will fail if can't be coerced to int 
                        inserts.append(unicode(tableItem.text()))
                    except:
                        if tableItem.text() == 'NA': 
                            inserts.append(unicode(tableItem.text()))
                            print 'set NA'
                        elif tableItem.text() == '1.#QNAN': 
                            inserts.append('NA') #if we read in some data
                            print 'set QNAN to NA'
                        else: 
                            inserts.append('"'+unicode(tableItem.text())+'"')
                            print unicode(tableItem.text())+' set as text'

            insert = ','.join(inserts)
            element += insert+')'
            if self.classes:
                element += self.classes[j-1][1]
            rinsertion.append(element)
            
        rinsert = ','.join(rinsertion)

        if len(rownames) > 0:
            rname = []
            for i in rowi:
                if rownames[unicode(i)] in rname:
                    rname.append(rownames[unicode(i)]+'_at_'+unicode(i))
                else:
                    rname.append(rownames[unicode(i)])
            rnf = '","'.join(rname)
            rinsert += ', row.names =c("'+rnf+'")' 
        self.R(self.Rvariables['table']+'<-data.frame('+rinsert+')', wantType = 'NoConversion')
        
        # make a new data table, we copy the dictAttrs from the incoming table but nothing more, as a patch for cm managers we also remove the cm from the dictAttrs if one exists
        
        self.newData = redRRDataFrame(data = self.Rvariables['table'], parent = self.Rvariables['table'])
        
        self.rSend('Data Table', self.newData)
Example #16
0
    def commitTable(self):
        #run through the table and make the output
        try:
            trange = self.dataTable.selectedRanges()[0]
        except:
            trange = None
        if trange and trange.leftColumn() == trange.rightColumn() and trange.topRow() == trange.bottomRow():
            rowi = range(0, self.maxRow+1)
            coli = range(0, self.maxCol+1)
        else:
            rowi = range(trange.topRow(), trange.bottomRow())
            coli = range(trange.leftColumn(), trange.rightColumn()+1)
            
       
        rownames = {}  
        colnames = {}        
        #if 'Use Row Headers' in self.rowHeaders.getChecked():
            
        for i in rowi:
            item = self.dataTable.item(i, coli[0])
            if item != None:
                thisText = item.text()
            else: thisText = unicode(i)
            if thisText == None or thisText == '':
                thisText = unicode(i)
                
            rownames[unicode(i)] = (unicode(thisText))
        coli = coli[1:] #index up the cols

       # if 'Use Column Headers' in self.rowHeaders.getChecked():
        for j in coli:
            item = self.dataTable.horizontalHeaderItem(j)
            if item != None:
                thisText = item.text()
            else: thisText = '"'+unicode(j)+'"'
            if thisText == None or thisText == '':
                thisText = '"'+unicode(j)+'"'
            thisText = thisText.split(' ')[0]
            colnames[unicode(j)] = (unicode(thisText))

        rinsertion = []
        
        for j in coli:
            element = ''
            if colnames:
                element += colnames[unicode(j)]+'='
            # if self.classes:
                # element += self.classes[j-1][0]
            element += 'c('
            inserts = []
            for i in rowi:

                tableItem = self.dataTable.item(i,j)
                if tableItem == None:
                    inserts.append('NA')
                else:
                    try: #catch if the element can be coerced to numeric in the table
                        float(tableItem.text()) #will fail if can't be coerced to int 
                        inserts.append(unicode(tableItem.text()))
                    except:
                        if tableItem.text() == 'NA': 
                            inserts.append(unicode(tableItem.text()))
                            print 'set NA'
                        elif tableItem.text() == '1.#QNAN': 
                            inserts.append('NA') #if we read in some data
                            print 'set QNAN to NA'
                        else: 
                            inserts.append('"'+unicode(tableItem.text())+'"')
                            print unicode(tableItem.text())+' set as text'

            insert = ','.join(inserts)
            element += insert+')'
            if self.classes:
                element += self.classes[j-1][1]
            rinsertion.append(element)
            
        rinsert = ','.join(rinsertion)

        if len(rownames) > 0:
            rname = []
            for i in rowi:
                if rownames[unicode(i)] in rname:
                    rname.append(rownames[unicode(i)]+'_at_'+unicode(i))
                else:
                    rname.append(rownames[unicode(i)])
            rnf = '","'.join(rname)
            rinsert += ', row.names =c("'+rnf+'")' 
        self.R(self.Rvariables['table']+'<-data.frame('+rinsert+')', wantType = 'NoConversion')
        
        # make a new data table, we copy the dictAttrs from the incoming table but nothing more, as a patch for cm managers we also remove the cm from the dictAttrs if one exists
        
        self.newData = redRRDataFrame(data = self.Rvariables['table'], parent = self.Rvariables['table'])
        
        self.rSend("id0", self.newData)
        self.processDF(self.newData)  ## a good way to ensure loading and saving.
        

            
Example #17
0
    def functionCommit(self):
        try:
            if unicode(self.dialogTopLineEdit.text()) != '':
                topText = unicode(self.dialogTopLineEdit.text())
                try:
                    a = float(topText)
                except:
                    self.status.setText(
                        _('Top Text Area Does Not Contain A Number'))
                    return
            else:
                topText = self.data + '$' + unicode(
                    self.dialogTopListBox.selectedItems()[0].text())

            if self.dialogBottomArea.isVisible():
                if unicode(self.dialogBottomLineEdit.text()) != '':
                    bottomText = unicode(self.dialogBottomLineEdit.text())
                    try:
                        if unicode(self.dialogLabel.text()) not in ['match']:
                            a = float(bottomText)
                    except:
                        self.status.setText(
                            _('Top Text Area Does Not Contain A Number'))
                        return
                else:
                    bottomText = self.data + '$' + unicode(
                        self.dialogBottomListBox.selectedItems()[0].text())

            function = unicode(self.dialogLabel.text())

            if function in [
                    'log10', 'log2', 'as.numeric', 'as.character', 'exp'
            ]:
                try:
                    self.R(self.data + '$' + function + unicode(self.counter) +
                           '<-' + function + '(' + topText + ')',
                           wantType='NoConversion')
                    self.table.setRTable(self.data)
                    self.counter += 1
                except:
                    self.status.setText(_('An error occured in your function'))
            elif function in [
                    'toDateTime (MDY)', 'toDateTime(YMD)', 'toDateTime(DMY)'
            ]:
                if function == 'toDateTime (MDY)':
                    self.R(self.data + '$dateAsMDY' + unicode(self.counter) +
                           '<-strptime(' + topText + ', "%m/%d/%y")',
                           wantType='NoConversion')
                elif function == 'toDateTime (YMD)':
                    self.R(self.data + '$dateAsMDY' + unicode(self.counter) +
                           '<-strptime(' + topText + ', "%y/%m/%d")',
                           wantType='NoConversion')
                elif function == 'toDateTime (DMY)':
                    self.R(self.data + '$dateAsMDY' + unicode(self.counter) +
                           '<-strptime(' + topText + ', "%d/%m/%y")',
                           wantType='NoConversion')
            elif function in ['match']:
                try:
                    self.R(self.data + '$' + function + unicode(self.counter) +
                           '<-' + function + '(' + topText + ', ' +
                           bottomText + ')',
                           wantType='NoConversion')
                    self.table.setRTable(self.data)
                    self.counter += 1
                except:
                    self.status.setText(_('An error occured in your function'))
            else:
                if function == 'add':
                    try:
                        self.R(self.data + '$' + 'plus_' +
                               unicode(self.counter) + '<-' + topText + ' + ' +
                               bottomText,
                               wantType='NoConversion')
                        self.table.setRTable(self.data)
                    except:
                        self.status.setText(
                            _('An error occured in your function'))
                elif function == 'subtract':
                    try:
                        self.R(self.data + '$' + 'minus_' +
                               unicode(self.counter) + '<-' + topText + ' - ' +
                               bottomText,
                               wantType='NoConversion')
                        self.table.setRTable(self.data)
                    except:
                        self.status.setText(
                            _('An error occured in your function'))
                elif function == 'multiply':
                    try:
                        self.R(self.data + '$' + 'times_' +
                               unicode(self.counter) + '<-as.numeric(' +
                               topText + ') * as.numeric(' + bottomText + ')',
                               wantType='NoConversion')
                        self.table.setRTable(self.data)
                    except:
                        self.status.setText(
                            _('An error occured in your function'))
                elif function == 'divide':
                    try:
                        self.R(self.data + '$' + 'divide_' +
                               unicode(self.counter) + '<-as.numeric(' +
                               topText + ') / as.numeric(' + bottomText + ')',
                               wantType='NoConversion')
                        self.table.setRTable(self.data)
                    except:
                        self.status.setText(
                            _('An error occured in your function'))
                elif function == 'logicAND':
                    try:
                        self.R(self.data + '$' + 'logic_AND' +
                               unicode(self.counter) + '<-' + topText + '&' +
                               bottomText,
                               wantType='NoConversion')
                    except:
                        self.status.setText(
                            _('An error occured in your function'))
                elif function == 'logicOR':
                    try:
                        self.R(self.data + '$' + 'logic_OR' +
                               unicode(self.counter) + '<-' + topText + '|' +
                               bottomText,
                               wantType='NoConversion')
                    except:
                        self.status.setText(
                            _('An error occured in your function'))
                self.counter += 1
            self.dialogBottomListBox.update(
                self.R('colnames(' + self.data + ')', wantType='list'))
            self.dialogTopListBox.update(
                self.R('colnames(' + self.data + ')', wantType='list'))
            newData = redRRDataFrame(data=self.data, parent=self.data)
            self.rSend("id0", newData)
            self.dialog.hide()
        except:
            self.status.setText(_('An error occured in your function'))
Example #18
0
    def commitTable(self):
        #run through the table and make the output
        
        #self.dataTable.getData()
        
        trange = self.dataTable.selectedRanges()[0]
        
        #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, ','.join([str(a) for a in trange.leftColumn(), trange.rightColumn(), trange.topRow(), trange.bottomRow()]))
        if trange.leftColumn() == trange.rightColumn() and trange.topRow() == trange.bottomRow():
            rowi = range(0, self.maxRow+1)
            coli = range(0, self.maxCol+1)
        else:

            rowi = range(trange.topRow(), trange.bottomRow()+1)
            coli = range(trange.leftColumn(), trange.rightColumn()+1)
            
        if self.dataTable.item(rowi[0], coli[0]) == None: 
            #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Setting row and col headers to true')
            self.rowHeaders.setChecked(['Use Row Headers', 'Use Column Headers'])
            #self.rowHeaders.setChecked(['Use Column Headers'])
        rownames = {}
        colnames = {}
        if 'Use Row Headers' in self.rowHeaders.getChecked():
            #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Using Row headers')
            for i in rowi:
                item = self.dataTable.item(i, coli[0])
                if item != None:
                    thisText = item.text()
                else: thisText = unicode(i)
                if thisText == None or thisText == '':
                    thisText = unicode(i)
                    
                rownames[unicode(i)] = unicode(thisText)
            coli = coli[1:] #index up the cols

        if 'Use Column Headers' in self.rowHeaders.getChecked():
            #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'Using col headers')
            for j in coli:
                item = self.dataTable.item(rowi[0], j)
                if item != None:
                    thisText = item.text()
                else: thisText = '"'+unicode(j)+'"'
                if thisText == None or thisText == '':
                    thisText = '"'+unicode(j)+'"'
                thisText = thisText.split(' ')[0]
                colnames[unicode(j)] = (unicode(thisText))
            #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, unicode(colnames))
            rowi = rowi[1:]
        rinsertion = []
        
        for j in coli:
            element = ''
            if colnames:
                element += colnames[unicode(j)]+'='
            if self.classes:
                element += self.classes[j-1][0]
            element += 'c('
            inserts = []
            for i in rowi:
                #redRLog.log(redRLog.REDRCORE, redRLog.DEBUG, 'inserting data in cell i %s, j %s' % (i, j))
                tableItem = self.dataTable.item(i,j)
                if tableItem == None:
                    inserts.append('NA')
                else:
                    try: #catch if the element can be coerced to numeric in the table
                        float(tableItem.text()) #will fail if can't be coerced to int 
                        inserts.append(unicode(tableItem.text()))
                    except:
                        if tableItem.text() == 'NA': 
                            inserts.append(unicode(tableItem.text()))
                            print 'set NA'
                        elif tableItem.text() == '1.#QNAN': 
                            inserts.append('NA') #if we read in some data
                            print 'set QNAN to NA'
                        else: 
                            inserts.append('"'+unicode(tableItem.text())+'"')
                            print unicode(tableItem.text())+' set as text'

            insert = ','.join(inserts)
            element += insert+')'
            if self.classes:
                element += self.classes[j-1][1]
            rinsertion.append(element)
            
        rinsert = ','.join(rinsertion)

        if len(rownames) > 0:
            rname = []
            for i in rowi:
                if rownames[unicode(i)] in rname:
                    rname.append(rownames[unicode(i)]+'_at_'+unicode(i))
                else:
                    rname.append(rownames[unicode(i)])
            rnf = '","'.join(rname)
            rinsert += ', row.names =c("'+rnf+'")' 
        self.R(self.Rvariables['table']+'<-data.frame('+rinsert+')', wantType = 'NoConversion')
        
        # make a new data table, we copy the dictAttrs from the incoming table but nothing more, as a patch for cm managers we also remove the cm from the dictAttrs if one exists
        
        self.newData = redRRDataFrame(data = self.Rvariables['table'], parent = self.Rvariables['table'])
        
        self.rSend('Data Table', self.newData)
Example #19
0
    def commitTable(self):
        #run through the table and make the output
        try:
            trange = self.dataTable.selectedRanges()[0]
        except:
            trange = None
        if trange == None or (trange.leftColumn() == trange.rightColumn() and trange.topRow() == trange.bottomRow()):
            rowi = range(0, self.maxRow+1)
            coli = range(0, self.maxCol+1)
        else:
            rowi = range(trange.topRow(), trange.bottomRow())
            coli = range(trange.leftColumn(), trange.rightColumn()+1)
            
       
        rownames = {}  
        colnames = {}        
        #if 'Use Row Headers' in self.rowHeaders.getChecked():
            
        for i in rowi:
            item = self.dataTable.item(i, coli[0])
            if item != None:
                thisText = item.text()
            else: thisText = unicode(i)
            if thisText == None or thisText == '':
                thisText = unicode(i)
                
            rownames[unicode(i)] = (unicode(thisText))
        coli = coli[1:] #index up the cols

       # if 'Use Column Headers' in self.rowHeaders.getChecked():
        for j in coli:
            item = self.dataTable.horizontalHeaderItem(j)
            if item != None:
                thisText = item.text()
            else: thisText = '"'+unicode(j)+'"'
            if thisText == None or thisText == '':
                thisText = '"'+unicode(j)+'"'
            thisText = thisText.split(' ')[0]
            colnames[unicode(j)] = (unicode(thisText))

        rinsertion = []
        
        for j in coli:
            element = ''
            if colnames:
                element += colnames[unicode(j)]+'='
            # if self.classes:
                # element += self.classes[j-1][0]
            element += 'c('
            inserts = []
            for i in rowi:

                tableItem = self.dataTable.item(i,j)
                if tableItem == None:
                    inserts.append('NA')
                else:
                    try: #catch if the element can be coerced to numeric in the table
                        float(tableItem.text()) #will fail if can't be coerced to int 
                        inserts.append(unicode(tableItem.text()))
                    except:
                        if tableItem.text() == 'NA': 
                            inserts.append(unicode(tableItem.text()))
                            print 'set NA'
                        elif tableItem.text() == '1.#QNAN': 
                            inserts.append('NA') #if we read in some data
                            print 'set QNAN to NA'
                        else: 
                            inserts.append('"'+unicode(tableItem.text())+'"')
                            print unicode(tableItem.text())+' set as text'

            insert = ','.join(inserts)
            element += insert+')'
            if self.classes:
                element += self.classes[j-1][1]
            rinsertion.append(element)
            
        rinsert = ','.join(rinsertion)

        if len(rownames) > 0:
            rname = []
            for i in rowi:
                if rownames[unicode(i)] in rname:
                    rname.append(rownames[unicode(i)]+'_at_'+unicode(i))
                else:
                    rname.append(rownames[unicode(i)])
            rnf = '","'.join(rname)
            rinsert += ', row.names =c("'+rnf+'")' 
        self.R(self.Rvariables['table']+'<-data.frame('+rinsert+')', wantType = 'NoConversion')
        
        # make a new data table, we copy the dictAttrs from the incoming table but nothing more, as a patch for cm managers we also remove the cm from the dictAttrs if one exists
        
        self.newData = redRRDataFrame(self, data = self.Rvariables['table'], parent = self.Rvariables['table'])
        
        self.rSend("id0", self.newData)
        self.processDF(self.newData)  ## a good way to ensure loading and saving.