Skip to content
Advertisement

Calling an R package function with rpy2

I’m new to R and need to pass string data from a pandas dataframe to a function in R. This function accepts nested lists of strings, such as:

> 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"  

The code

# 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')
   

I tried two approaches:

1)

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

That yielded KeyError: <class 'list'> error message.

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')

That yielded the error message:

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

I checked if d is a list or not:

robjects.r(f'print(is.list(d))')

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

I’d be grateful to get any suggestion regarding how to call ontology_similarity.get_sim_grid().
Thanks.

Advertisement

Answer

Eventually I used robjects.r to call the R package from R instead of from Python, and it worked.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement