本文整理汇总了Python中rpy2.robjects.StrVector方法的典型用法代码示例。如果您正苦于以下问题:Python robjects.StrVector方法的具体用法?Python robjects.StrVector怎么用?Python robjects.StrVector使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rpy2.robjects
的用法示例。
在下文中一共展示了robjects.StrVector方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _convert_vector
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def _convert_vector(obj):
if isinstance(obj, robj.IntVector):
return _convert_int_vector(obj)
elif isinstance(obj, robj.StrVector):
return _convert_str_vector(obj)
# Check if the vector has extra information attached to it that can be used
# as an index
try:
attributes = set(r['attributes'](obj).names)
except AttributeError:
return list(obj)
if 'names' in attributes:
return pd.Series(list(obj), index=r['names'](obj))
elif 'tsp' in attributes:
return pd.Series(list(obj), index=r['time'](obj))
elif 'labels' in attributes:
return pd.Series(list(obj), index=r['labels'](obj))
if _rclass(obj) == 'dist':
# For 'eurodist'. WARNING: This results in a DataFrame, not a Series or list.
matrix = r['as.matrix'](obj)
return convert_robj(matrix)
else:
return list(obj)
示例2: plot_module_eigengene
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def plot_module_eigengene(self, module):
'''
barchart illustrating module eigengene
'''
eigengene = self.eigengenes.get_module_eigengene(module)
params = {}
params['height'] = base().as_numeric(eigengene)
limit = max(abs(base().max(eigengene)[0]), abs(base().min(eigengene)[0]))
ylim = [-1 * limit, limit]
params['ylim'] = ro.IntVector(ylim)
colors = ["red" if e[0] > 0 else "blue" for e in eigengene]
params['col'] = ro.StrVector(colors)
params['border'] = ro.NA_Logical
params['las'] = 2
params['names.arg'] = ro.StrVector(self.eigengenes.samples())
params['cex.names'] = 0.6
params['main'] = "Eigengene: " + module
manager = RManager(eigengene, params)
manager.barchart()
示例3: update_membership
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def update_membership(self, genes, blocks):
'''
fetches new module membership from WGCNA
blocks and updates relevant genes
'''
modules = rsnippets.extractModules(blocks, ro.StrVector(genes))
# if the feature is in the subset
# update, otherwise leave as is
for gene in genes:
# .rx returns a FloatVector which introduces
# a .0 to the numeric labels when converted to string
# which needs to be removed
# note: R array starts at index 1, python at 0
module = str(modules.rx(gene, 1)[0]).replace('.0', '')
if module in ('0', 'grey'):
module = 'UNCLASSIFIED'
else:
module = self.iteration + '_' + 'M' + str(module)
self.__update_classified_iteration(gene, self.iteration)
self.__update_module(gene, module)
return None
示例4: barPlot
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def barPlot(dict_, keysInOrder=None, printCounts=True, ylim=None, *args, **kwdargs):
""" Plot a bar plot
Args:
dict_: a dictionary of name -> value, where value is the height of the bar
use a collections.OrderedDict() to easily convey the order of the groups
keysInOrder: an optional ordering of the keys in dict_ (alternate option to using collections.OrderedDict)
printCounts: option to print the counts on top of each bar
additional kwdargs are passed directly to r.barplot()
"""
if not keysInOrder:
keysInOrder = dict_.keys()
heights = ro.FloatVector([dict_[key] for key in keysInOrder])
kwdargs["names.arg"] = ro.StrVector(keysInOrder)
if ylim is None:
if printCounts:
ylim = [min(heights), max(heights)*1.1]
else:
ylim = [min(heights), max(heights)]
x = r.barplot(heights, ylim=ro.FloatVector(ylim), *args, **kwdargs)
if printCounts:
heightsStrings = ["{:.2g}".format(height) for height in heights]
r.text(x, ro.FloatVector(heights), ro.StrVector(heightsStrings), pos=3)
return x
示例5: extract_subset
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def extract_subset(self, modules):
'''
return a submatrix
'''
if self.debug:
self.logger.debug("Extracting eigengenes for the following modules:")
self.logger.debug(modules)
if self.debug:
self.logger.debug("Converting module list to ro.StrVector; see R-log")
ro.r("print('Converting module list to ro.StrVector to extract eigengenes:')")
vector = ro.StrVector(modules)
if self.debug:
self.logger.debug(vector)
if self.debug:
self.logger.debug("Extracted submatrix, see R-log")
ro.r("print('Extracted eigengene submatrix:')")
newMatrix = self.matrix.rx(vector, True)
if self.debug:
self.logger.debug(newMatrix)
return newMatrix
示例6: heatmap_annotation_data_frame
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def heatmap_annotation_data_frame(self, categories, annotation):
'''
takes a dict of gene->value and creates a data frame
data frame
assume annotation is an ordered dict
updates column names to names
'''
df = base().as_data_frame(base().t(ro.DataFrame(annotation)))
df.colnames = ro.StrVector(categories)
return df
示例7: heatmap_annotation_key
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def heatmap_annotation_key(self, name, colors):
'''
generates data frame for color key for the annotation
from a dict
'''
keyColors = ro.StrVector([c for c in colors.values()])
keyColors.names = colors.keys()
key = OrderedDict()
key[name] = keyColors
return ro.ListVector(key)
示例8: calculate_degree_modularity
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def calculate_degree_modularity(self, targetModule):
'''
calculates in degree (kIn) and out degree (kOut)
for the target module
'''
members = self.__get_module_members(targetModule)
degree = rsnippets.degree(self.adjacency, ro.StrVector(members),
self.args.edgeWeight)
self.modules[targetModule]['kIn'] = int(degree.rx2('kIn')[0])
self.modules[targetModule]['kOut'] = int(degree.rx2('kOut')[0])
size = self.modules[targetModule]['size']
self.modules[targetModule]['density'] = float(self.modules[targetModule]['kIn'])/(float(size) * (float(size) - 1.0)/2.0)
示例9: module_eigengenes
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def module_eigengenes(self, membership):
'''
wrapper for moduleEigengenes function
calculates eigengenes from profiles &
module membership (gene -> membership dict)
'''
if self.debug:
self.logger.debug("Running WGCNA moduleEigengenes function")
self.logger.debug("Module assignments:")
self.logger.debug(membership)
params = {}
params['softPower'] = self.params['power'] if 'power' in self.params else 6
params['expr'] = base().as_data_frame(self.transpose_data())
if self.debug:
self.logger.debug("Converting membership list to ro.StrVector; see R-log")
ro.r("print('Converting membership list to ro.StrVector for WGCNA moduleEigengenes:')")
params['colors'] = ro.StrVector(list(membership))
if self.debug:
self.logger.debug(params['colors'])
return wgcna().moduleEigengenes(**params)
示例10: load_membership
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def load_membership(self, fileName=None):
'''
loads membership
'''
if fileName is None:
fileName = "final-membership.txt"
membership = ro.DataFrame.from_csvfile(fileName, sep='\t',
header=True, row_names=1, as_is=True)
if self.debug:
self.logger.debug("Loaded membership from file " + fileName + "; see R-log")
ro.r("print('Loaded membership from file -- head of file:')")
self.logger.debug(membership.head())
index = membership.names.index('Module') + 1 # add 1 b/c of python/rpy2/R inconsistency
if self.debug:
self.logger.debug("Adjusted index of Module column: " + str(index))
classifiedCount = 0
unclassifiedCount = 0
for g in self.genes:
gStr = ro.StrVector([str(g)])
# strange, but necessary so that rpy2 will treat numeric gene ids as strings
# python str() conversion did not work
module = membership.rx(gStr[0], index)[0]
if module == 'UNCLASSIFIED':
unclassifiedCount = unclassifiedCount + 1
else:
classifiedCount = classifiedCount + 1
self.__update_module(g, module)
self.logger.info("Loaded " + str(classifiedCount) + " classified genes")
self.logger.info("Loaded " + str(unclassifiedCount) + " unclassified genes")
示例11: test_init_from_OrdDict
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def test_init_from_OrdDict():
od = rlc.OrdDict(c=(('a', robjects.IntVector((1,2))),
('b', robjects.StrVector(('c', 'd')))
))
dataf = robjects.DataFrame(od)
assert dataf.rx2('a')[0] == 1
示例12: test_init_from_dict
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def test_init_from_dict():
od = {'a': robjects.IntVector((1,2)),
'b': robjects.StrVector(('c', 'd'))}
dataf = robjects.DataFrame(od)
assert dataf.rx2('a')[0] == 1
示例13: test_init_stringsasfactors
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def test_init_stringsasfactors():
od = {'a': robjects.IntVector((1,2)),
'b': robjects.StrVector(('c', 'd'))}
dataf = robjects.DataFrame(od, stringsasfactor=True)
assert isinstance(dataf.rx2('b'), robjects.FactorVector)
dataf = robjects.DataFrame(od, stringsasfactor=False)
assert isinstance(dataf.rx2('b'), robjects.StrVector)
示例14: test_to_csvfile
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def test_to_csvfile():
fh = tempfile.NamedTemporaryFile(mode = "w", delete = False)
fh.close()
d = {'letter': robjects.StrVector('abc'),
'value' : robjects.IntVector((1, 2, 3))}
dataf = robjects.DataFrame(d)
dataf.to_csvfile(fh.name)
dataf = robjects.DataFrame.from_csvfile(fh.name)
assert dataf.nrow == 3
assert dataf.ncol == 2
示例15: test_colnames_set
# 需要导入模块: from rpy2 import robjects [as 别名]
# 或者: from rpy2.robjects import StrVector [as 别名]
def test_colnames_set():
dataf = robjects.r('data.frame(a=1:2, b=I(c("a", "b")))')
dataf.colnames = robjects.StrVector('de')
assert tuple(dataf.colnames) == ('d', 'e')