使用rpy2调用R包函数



我是R的新手,需要将字符串数据从pandas数据框架传递给R中的函数。该函数接受嵌套的字符串列表,例如:

> list(c("HP:0001315", "HP:0011343"), c("HP:0007164", "HP:0030810"), c( "HP:0030133", "HP:0040082"))
[[1]]
[1] "HP:0001315" "HP:0011343"
[[2]]
[1] "HP:0007164" "HP:0030810"
[[3]]
[1] "HP:0030133" "HP:0040082"  

# Importing the package `ontologySimilarity`:
from rpy2.robjects.packages import importr
import rpy2.robjects as robjects
utils = importr('utils')
utils.data('hpo')
ontology_similarity = importr('ontologySimilarity')

我尝试了两种方法:

1)

lists = numbers_and_ids.HPO_ID.str.split('t')
ontology_similarity.get_sim_grid(ontology='hpo', term_sets=lists)

产生KeyError: <class 'list'>错误消息。

2)

# numbers_and_ids dataframe from which the data will be taken:
data = {'dna_#': {0: '25246', 1: '29244', 2: '6409'},
'HPO_ID': {0: 'HP:0001263tHP:0001508tHP:0000252tHP:0001875tHP:0001627', 1: 'HP:0011344tHP:0008936tHP:0001257tHP:0005305tHP:0002188tHP:0040187tHP:0000365tHP:0001999', 2: 'HP:0001263tHP:0000252tHP:0001629tHP:0001875tHP:0001999'}}
numbers_and_ids = pandas.DataFrame(data}
numbers_and_ids
Out[89]:19:00
dna_#                                             HPO_ID
0  25246  HP:0001263tHP:0001508tHP:0000252tHP:0001875...
1  29244  HP:0011344tHP:0008936tHP:0001257tHP:0005305...
2   6409  HP:0001263tHP:0000252tHP:0001629tHP:0001875...
# Converting the data in the dataframe into tuples:
_1 = tuple(numbers_and_ids.HPO_ID.str.split('t')[0])
_2 = tuple(numbers_and_ids.HPO_ID.str.split('t')[1])
_3 = tuple(numbers_and_ids.HPO_ID.str.split('t')[2])
# Creating the nested list d and calling the function:
robjects.r(f'd<-list(c{_1}, c{_2}, c{_3})')
ontology_similarity.get_sim_grid(ontology='hpo', term_sets='d')

产生错误消息:

rpy2.rinterface_lib.embedded.RRuntimeError: Error in (function (ontology, information_content, term_sim_method, term_sim_mat,  : 
is.list(term_sets) & is.list(term_sets) is not TRUE

我检查了d是否是一个列表:

robjects.r(f'print(is.list(d))')
[1] TRUE
Out[92]: 
<rpy2.robjects.vectors.BoolVector object at 0x7f591524a900> [RTYPES.LGLSXP]
R classes: ('logical',)
[       1]

谢谢。 请告诉我如何呼叫ontology_similarity.get_sim_grid()

最后,我使用robjects.r从R而不是从Python调用R包,它工作了。

最新更新