在Django中使用rpy2和biomaRt
我用R语言写了一个程序,通过biomaRt库找出了数据库中的所有候选基因。现在我想用rpy2把这个R脚本转换成Python文件。
下面是我写的有效的R脚本。
library(biomaRt)
mart <- useMart(biomart="ensembl", dataset="hsapiens_gene_ensembl")
positions <- read.table("positions.txt")
names(positions) <- c("chr","start","stop")
positions$start <- positions$start - 650000
positions$stop <- positions$stop + 650000
filterlist <- list(positions$chr,positions$start,positions$stop,"protein_coding")
getBM(attributes = c("hgnc_symbol","entrezgene", "chromosome_name",
"start_position", "end_position"), filters = c("chromosome_name", "start",
"end", "biotype"), values = filterlist, mart = mart)
我该如何使用rpy2把上面的R脚本转换成Python脚本呢?
from rpy2.robjects import r as R
R.library("biomaRt")
mart = R.useMart(biomart="ensembl",dataset="hsapiens_gene_ensembl")
position = R.list("7","110433484", "110433544")
filterlist = R.list(position[0],position[1],position[2],"protein_coding")
result = R.getBM(attributes = ("hgnc_symbol","entrezgene", "chromosome_name",
"start_position", "end_position") ,filters = ("chromosome_name",
"start", "end", "biotype"), values = filterlist, mart = mart)
最后一行的错误信息:
result = R.getBM(attributes = ("hgnc_symbol","entrezgene", "chromosome_name",
"start_position", "end_position") ,filters = ("chromosome_name",
"start", "end", "biotype"), values = filterlist, mart = mart)
提示内容是:
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "/Users/project/lib/python2.7/site-packages/rpy2/robjects/functions.py", line 86, in __call__
return super(SignatureTranslatedFunction, self).__call__(*args, **kwargs)
File "/Users/project/lib/python2.7/site-packages/rpy2/robjects/functions.py", line 34, in __call__
new_kwargs[k] = conversion.py2ri(v)
File "/Users/project/lib/python2.7/site-packages/rpy2/robjects/__init__.py", line 148, in default_py2ri
raise(ValueError("Nothing can be done for the type %s at the moment." %(type(o))))
ValueError: Nothing can be done for the type <type 'tuple'> at the moment.
有没有人知道如何用rpy2转换成Python,并且如何把Python代码嵌入到Django中,以便我可以展示数据呢?
1 个回答
1
根据错误提示,Python中的类型tuple
不会自动转换。
你可以尝试以下方法:
from rpy2.robjects.vectors import StrVector
result = R.getBM(attributes = StrVector(("hgnc_symbol","entrezgene", "chromosome_name",
"start_position", "end_position")),
filters = StrVector(("chromosome_name",
"start", "end", "biotype")),
values = filterlist,
mart = mart)
注意:虽然可以创建一个函数来猜测用户的意图,但我认为这样可能会引发很多问题。你可以通过实现自己的额外转换来进行定制。或者,你也可以让rpy2把Python中的list
转换成R语言的列表,然后再进行unlist
操作。
from rpy2.robjects.packages import importr
base = importr('base')
ul = base.unlist
result = R.getBM(attributes = ul(["hgnc_symbol","entrezgene", "chromosome_name",
"start_position", "end_position"]),
filters = ul(["chromosome_name",
"start", "end", "biotype"]),
values = filterlist,
mart = mart)