当前位置: 首页>>代码示例>>Python>>正文


Python robjects.r方法代码示例

本文整理汇总了Python中rpy2.robjects.r方法的典型用法代码示例。如果您正苦于以下问题:Python robjects.r方法的具体用法?Python robjects.r怎么用?Python robjects.r使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rpy2.robjects的用法示例。


在下文中一共展示了robjects.r方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: plotInsertSizeDistribution

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def plotInsertSizeDistribution(isd, sampleName, dataHub):
    try:
        from rpy2 import robjects as ro

        d = tempfile.mkdtemp()
        filename = os.path.join(d, sampleName)

        if not filename.endswith(".png"):
            filename += ".png"

        ro.r.png(filename, res=250, width=1200, height=1200)

        alleles = ["alt", "ref", "amb"]
        others = [[len(chosenSet) for chosenSet in dataHub.samples[sampleName].chosenSets(allele)] for allele in alleles]
        plotting.ecdf([isd.insertSizes]+others, ["average"]+alleles, xlab="Insert size (bp)", main=sampleName, legendWhere="bottomright", lwd=2)
        
        ro.r["dev.off"]()

        data = open(filename).read()
        return data
    except ImportError:
        return None 
开发者ID:svviz,项目名称:svviz,代码行数:24,代码来源:insertsizes.py

示例2: rpyEdgeR

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def rpyEdgeR(data, groups, sizes, genes):
    """Run edgeR analysis - from http://bcbio.wordpress.com/ """

    import rpy2.robjects as robjects
    import rpy2.robjects.numpy2ri
    rpy2.robjects.numpy2ri.activate()
    robjects.r('''library(edgeR)''')
    params = {'group' : groups, 'lib.size' : sizes}
    print (params)
    d = robjects.r.DGEList(counts=data, **params)
    print (d)
    robjects.r.calcNormFactors(d)
    robjects.r.estimateCommonDisp(d)
    robjects.r.estimateTagwiseDisp(d)
    robjects.r.exactTest(d)

    #ms = robjects.r.deDGE(dgelist, doPoisson=True)
    #tags = robjects.r.topTags(ms, pair=groups, n=len(genes))
    indexes = [int(t) - 1 for t in tags.rownames()]
    pvals = list(tags.r['adj.P.Val'][0])
    return 
开发者ID:dmnfarrell,项目名称:smallrnaseq,代码行数:23,代码来源:de.py

示例3: load_cv

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def load_cv(self, path):
        set_wd_str = 'setwd("{0}")'.format(os.getcwd())
        ro.r(set_wd_str)
        ro.r('load("{0}")'.format(path))
        self.rf_cv = ro.r["trained.models"]
        if new_pandas_flag:
            # rpy2 is a complete joke of a package
            try:
                # use this way for conversion for bugged rpy2 versions
                self.cv_folds = pandas2ri.ri2py(ro.r["cvFoldDf"])
            except:
                # this should be the correct way to convert
                # but several versions of rpy2 have a bug
                self.cv_folds = ro.r["cvFoldDf"]
        else:
            self.cv_folds = com.convert_robj(ro.r["cvFoldDf"]) 
开发者ID:KarchinLab,项目名称:2020plus,代码行数:18,代码来源:r_random_forest_clf.py

示例4: __initialize_R

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def __initialize_R(self, logType='run'):
        '''
        initialize R workspace and logs
        '''
        # set working directory
        base().setwd(self.args.workingDir)

        # suppress warnings
        ro.r['options'](warn=-1)

        # r log
        logFile = 'iterativeWGCNA-R.log'
        if logType == 'merge':
            logFile = 'adjust-merge-' + str(self.args.finalMergeCutHeight) + '-' + logFile

        rLogger = base().file(logFile, open='wt')
        base().sink(rLogger, type=base().c('output', 'message'))

        if self.args.enableWGCNAThreads:
            wgcna().enableWGCNAThreads() 
开发者ID:cstoeckert,项目名称:iterativeWGCNA,代码行数:22,代码来源:iterativeWGCNA.py

示例5: install_grf

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def install_grf(self):
        from rpy2.robjects.packages import importr
        import rpy2.robjects.packages as rpackages
        from rpy2.robjects.vectors import StrVector
        import rpy2.robjects as robjects

        robjects.r.options(download_file_method='curl')

        package_names = ["grf"]
        utils = rpackages.importr('utils')
        utils.chooseCRANmirror(ind=0)
        utils.chooseCRANmirror(ind=0)

        names_to_install = [x for x in package_names if not rpackages.isinstalled(x)]
        if len(names_to_install) > 0:
            utils.install_packages(StrVector(names_to_install))

        return importr("grf") 
开发者ID:d909b,项目名称:perfect_match,代码行数:20,代码来源:causal_forest.py

示例6: install_bart

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def install_bart(self):
        import rpy2.robjects.packages as rpackages
        from rpy2.robjects.packages import importr
        from rpy2.robjects.vectors import StrVector
        import rpy2.robjects as robjects

        robjects.r.options(download_file_method='curl')

        # install.packages("rJava")
        rj = importr("rJava", robject_translations={'.env': 'rj_env'})
        rj._jinit(parameters="-Xmx16g", force_init=True)
        print("rJava heap size is", np.array(rj._jcall(rj._jnew("java/lang/Runtime"), "J", "maxMemory"))[0] / 1e9,
              "GB.", file=sys.stderr)

        package_names = ["bartMachine"]
        utils = rpackages.importr('utils')
        utils.chooseCRANmirror(ind=0)
        utils.chooseCRANmirror(ind=0)

        names_to_install = [x for x in package_names if not rpackages.isinstalled(x)]
        if len(names_to_install) > 0:
            utils.install_packages(StrVector(names_to_install))

        return importr("bartMachine") 
开发者ID:d909b,项目名称:perfect_match,代码行数:26,代码来源:bart.py

示例7: scatterplots

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def scatterplots(self, df):
        """scatterplots of relationships"""
        import matplotlib.pyplot as plt
        fig, axes = plt.subplots(5, 2, figsize=(6.5, 9))
        df['log_pingtime_max'] = df.pingtime_max.apply(np.log)
        df['log_pingtime_mean'] = df.pingtime_mean.apply(np.log)

        yvars = ['log_pingtime_max', 'frechet_dist', 'gpsMatchRatio',
                 'matchGpsRatio', 'll_dist_mean', 'll_dist_min',
                 'll_topol_mean', 'll_topol_min', 'll_distratio_mean',
                 'll_distratio_min']
        for ii in range(0, 10):
            row = int(math.floor(ii/2.))
            col = ii % 2
            if ii >= len(yvars): break

            df[df.match_good == 1].plot.scatter('log_pingtime_mean', yvars[ii], ax=axes[row, col], color='g', s=2)
            df[df.match_good == 0].plot.scatter('log_pingtime_mean', yvars[ii], ax=axes[row, col], color='r', s=2)
        plt.tight_layout()
        fig.savefig(self.path+'pr_good_scatters.pdf') 
开发者ID:amillb,项目名称:pgMapMatch,代码行数:22,代码来源:mapmatcher.py

示例8: Multtest

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def Multtest(self,test_type):
        r('library("multtest")')
        filename = self.File()
        try: output_file = string.replace(filename,'input','output')
        except ValueError: output_file = filename[0:-4]+'-output.txt'
        print "Begining to process",filename
        parse_line = 'job<-read.table(%s,sep="\t", row.names=1, as.is=T)' % filename
        print_out = r(parse_line)
        print_out = r('matrix_size<-dim(job)')
        print_out = r('label<-job[1,2:matrix_size[2]]')
        print_out = r('jobdata<-job[2:matrix_size[1],2:matrix_size[2]]')
        if test_type == "f":
            print_out = r('ttest<-mt.maxT(jobdata,label, test="f", B=50000)')
        if test_type == "t":
            print_out = r('ttest<-mt.maxT(jobdata,label)')
        print_out = r('ttest2<-ttest[order(ttest[,1]),]')
        write_file = 'write.table(ttest2,%s,sep="\t")' % output_file
        print_out = r(write_file)
        print "Results written to:",output_file 
开发者ID:nsalomonis,项目名称:altanalyze,代码行数:21,代码来源:R_interface.py

示例9: _wrapper

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def _wrapper((context, conf, exact, seed)):
    """
    Helper, wrapper used for map_async callback

    Parameters
    ----------
    context :
        a discrimination context

    conf :
        confidence level

    exact :
        whether exact statistics should be computed

    seed :
        a seed for the random number generators

    Returns
    -------
    dict :
        discrimination statistics for the given context
    """

    # seed the PRNGs used to compute statistics
    logging.info('Computing stats for context %d' % context.num)
    ro.r('set.seed({})'.format(seed))
    np.random.seed(seed)
    return context.metric.compute(context.data, conf, exact=exact).stats 
开发者ID:columbia,项目名称:fairtest,代码行数:31,代码来源:multiple_testing.py

示例10: setUp

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def setUp(self):
        numpy2ri.activate()
        ro.r('set.seed({})'.format(0))
        np.random.seed(0) 
开发者ID:columbia,项目名称:fairtest,代码行数:6,代码来源:test_binary.py

示例11: __unicode__

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def __unicode__(self):
        s = 'Failed to parse and evaluate line %r.\nR error message: %r' % \
                (self.line, self.err)
        if self.stdout and (self.stdout != self.err):
            s += '\nR stdout:\n' + self.stdout
        return s 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:8,代码来源:rmagic.py

示例12: Rconverter

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def Rconverter(Robj, dataframe=False):
    """
    Convert an object in R's namespace to one suitable
    for ipython's namespace.

    For a data.frame, it tries to return a structured array.
    It first checks for colnames, then names.
    If all are NULL, it returns np.asarray(Robj), else
    it tries to construct a recarray

    Parameters
    ----------

    Robj: an R object returned from rpy2
    """
    is_data_frame = ro.r('is.data.frame')
    colnames = ro.r('colnames')
    rownames = ro.r('rownames') # with pandas, these could be used for the index
    names = ro.r('names')

    if dataframe:
        as_data_frame = ro.r('as.data.frame')
        cols = colnames(Robj)
        _names = names(Robj)
        if cols != ri.NULL:
            Robj = as_data_frame(Robj)
            names = tuple(np.array(cols))
        elif _names != ri.NULL:
            names = tuple(np.array(_names))
        else: # failed to find names
            return np.asarray(Robj)
        Robj = np.rec.fromarrays(Robj, names = names)
    return np.asarray(Robj) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:35,代码来源:rmagic.py

示例13: __init__

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def __init__(self, shell, Rconverter=Rconverter,
                 pyconverter=pyconverter,
                 cache_display_data=False):
        """
        Parameters
        ----------

        shell : IPython shell
        
        Rconverter : callable
            To be called on values taken from R before putting them in the
            IPython namespace.

        pyconverter : callable
            To be called on values in ipython namespace before 
            assigning to variables in rpy2.

        cache_display_data : bool
            If True, the published results of the final call to R are 
            cached in the variable 'display_cache'.

        """
        super(RMagics, self).__init__(shell)
        self.cache_display_data = cache_display_data

        self.r = ro.R()

        self.Rstdout_cache = []
        self.pyconverter = pyconverter
        self.Rconverter = Rconverter 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:32,代码来源:rmagic.py

示例14: Rpush

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def Rpush(self, line, local_ns=None):
        '''
        A line-level magic for R that pushes
        variables from python to rpy2. The line should be made up
        of whitespace separated variable names in the IPython
        namespace::

            In [7]: import numpy as np

            In [8]: X = np.array([4.5,6.3,7.9])

            In [9]: X.mean()
            Out[9]: 6.2333333333333343

            In [10]: %Rpush X

            In [11]: %R mean(X)
            Out[11]: array([ 6.23333333])

        '''
        if local_ns is None:
            local_ns = {}

        inputs = line.split(' ')
        for input in inputs:
            try:
                val = local_ns[input]
            except KeyError:
                try:
                    val = self.shell.user_ns[input]
                except KeyError:
                    # reraise the KeyError as a NameError so that it looks like
                    # the standard python behavior when you use an unnamed
                    # variable
                    raise NameError("name '%s' is not defined" % input)

            self.r.assign(input, self.pyconverter(val)) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:39,代码来源:rmagic.py

示例15: Rpull

# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import r [as 别名]
def Rpull(self, line):
        '''
        A line-level magic for R that pulls
        variables from python to rpy2::

            In [18]: _ = %R x = c(3,4,6.7); y = c(4,6,7); z = c('a',3,4)

            In [19]: %Rpull x  y z

            In [20]: x
            Out[20]: array([ 3. ,  4. ,  6.7])

            In [21]: y
            Out[21]: array([ 4.,  6.,  7.])

            In [22]: z
            Out[22]:
            array(['a', '3', '4'],
                  dtype='|S1')


        If --as_dataframe, then each object is returned as a structured array
        after first passed through "as.data.frame" in R before
        being calling self.Rconverter. 
        This is useful when a structured array is desired as output, or
        when the object in R has mixed data types. 
        See the %%R docstring for more examples.

        Notes
        -----

        Beware that R names can have '.' so this is not fool proof.
        To avoid this, don't name your R objects with '.'s...

        '''
        args = parse_argstring(self.Rpull, line)
        outputs = args.outputs
        for output in outputs:
            self.shell.push({output:self.Rconverter(self.r(output),dataframe=args.as_dataframe)}) 
开发者ID:ktraunmueller,项目名称:Computable,代码行数:41,代码来源:rmagic.py


注:本文中的rpy2.robjects.r方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。