使用函数从数据库中检索数据时出错

时间:2016-06-16 10:04:15

标签: r

我正在尝试从NCBI网站获取FASTA文件,我使用以下功能

getncbiseq <- function(accession){
  dbs <- c()
  for (i in 1:numdbs){
    db <- dbs[i]
    choosebank(db)
    resquery <- try(query(".tmpquery", paste("AC=", accession)),silent = TRUE)
    if (!(inherits(resquery, "try-error"))){
      queryname <- "query2"
      thequery <- paste("AC=",accession,sep="")
      query(`queryname`,`thequery`)
      # see if a sequence was retrieved:
      seq <- getSequence(query2$req[[1]])
      closebank()
      return(seq)
    }
    closebank()
  }
  print(paste("ERROR: accession",accession,"was not found"))
}    

当我尝试检索序列时

mydata <- getncbiseq("NC_001477")
  

getSequence出错(query2 $ req [[1]]):object&#39; query2&#39;找不到

还有更好的方法来缩短这些循环功能吗?

如果我使用

query('queryname','the query')
#or 
query("queryname","thequery")

我收到了另一个错误

  

查询错误(&#34; queryname&#34;,&#34; thequery&#34;):     无效请求:&#34;(^)处的未知列表:\&#34;(^)thequery \&#34;&#34;

2 个答案:

答案 0 :(得分:2)

我认为您打算将query()的电话号码分配给名为query2的变量,但您忘了这样做。试试这个:

if (!(inherits(resquery, "try-error"))) {
  queryname <- "query2"
  thequery <- paste("AC=", accession, sep="")
  query2 <- query(queryname, thequery)
  # see if a sequence was retrieved:
  seq <- getSequence(query2$req[[1]])
  closebank()
  return(seq)
}

正如你所提到的,你的其余代码也有一些怪癖和扭结,可能会有所改进。

<强>更新

以下是使用sapply向量上的dbs而不是显式for循环的代码的重构(后者通常是R人不赞成的):

processdbs <- function(x, y) {
    choosebank(x)
    resquery <- try(query(".tmpquery", paste("AC=", y)), silent = TRUE)
    if (!(inherits(resquery, "try-error"))) {
      queryname <- "query2"
      thequery  <- paste("AC=", y, sep="")
      query2 <- query(queryname, thequery)

      # see if a sequence was retrieved:
      seq <- getSequence(query2$req[[1]])
      closebank()
      return(seq)
    }
    closebank()
}

getncbiseq <- function(accession) {
   dbs <- c("genbank","refseq","refseqViruses","bacterial")
   result <- sapply(dbs, processdbs, y=accession)
   closebank()

   print(paste("ERROR: accession",accession,"was not found"))
}

您可能需要做一些额外的工作来检查result向量并确定是否在任何地方检索了序列。

答案 1 :(得分:2)

非常感谢你的帮助。我被困在这一天一整天。我终于在Windows 10下使用R3.4.0(32位)获得了以下代码: -

getncbiseq <- function(accession)
{
require("seqinr") # this function requires the SeqinR R package
# first find which ACNUC database the accession is stored in:
dbs <- c("genbank","refseq","refseqViruses","bacterial")
numdbs <- length(dbs)
for (i in 1:numdbs)
{
db <- dbs[i]
choosebank(db)
# check if the sequence is in ACNUC database 'db':
resquery <- try(query(".tmpquery", paste("AC=", accession)), silent = TRUE)

if (!(inherits(resquery, "try-error"))) {
  queryname <- "query2"
  thequery <- paste("AC=", accession, sep="")
  query2 <- query(queryname, thequery)
  # see if a sequence was retrieved:
  seq <- getSequence(query2$req[[1]])
  closebank()
  return(seq)
}
closebank()
}
print(paste("ERROR: accession",accession,"was not found"))
}