将API调用转换为数据帧的问题

时间:2016-02-10 12:35:56

标签: r api dataframe rjson

我想从comtrade数据库中的API调用中创建一个数据帧。 comtrade数据库提供此代码。然而,为我的参数修改它不会产生希望的结果。

代码如下所示:

library("rjson")
string <- get.Comtrade(px = "HS", ps = "2002" , p = "124" , r = "842" , fmt = "json")
reporters <- fromJSON(file = string)
reporters <- as.data.frame(t(sapply(reporters$results,rbind)))

get.Comtrade <- function(url = "http://comtrade.un.org/api/get?"
                         ,maxrec = 50000
                         ,type = "C"
                         ,freq = "A"
                         ,px = "HS"
                         ,ps = "now"
                         ,r = ""
                         ,p = ""
                         ,rg = "all"
                         ,cc = "TOTAL"
                         ,fmt = "json") {
  string <- paste(
    url
    ,"max=",maxrec,"&" #maximum no. of records returned
    ,"type=",type,"&" #type of trade (c=commodities)
    ,"freq=",freq,"&" #frequency
    ,"px=",px,"&" #classification
    ,"ps=",ps,"&" #time period
    ,"r=",r,"&" #reporting area
    ,"p=",p,"&" #partner country
    ,"rg=",rg,"&" #trade flow
    ,"cc=",cc,"&" #classification code
    ,"fmt=",fmt        #Format
    ,sep = ""
  )

  if (fmt == "csv") {
    raw.data <- read.csv(string,header = TRUE)
    return(list(validation = NULL, data = raw.data))
  } else {
    if (fmt == "json") {
      raw.data <- fromJSON(file = string)
      data <- raw.data$dataset
      validation <- unlist(raw.data$validation, recursive = TRUE)
      ndata <- NULL
      if (length(data) > 0) {
        var.names <- names(data[[1]])
        data <- as.data.frame(t(sapply(data,rbind)))
        ndata <- NULL
        for (i in 1:ncol(data)) {
          data[sapply(data[,i],is.null),i] <- NA
          ndata <- cbind(ndata, unlist(data[,i]))
        }
        ndata <- as.data.frame(ndata)
        colnames(ndata) <- var.names
      }
      return(list(validation = validation,data = ndata))
    }
  }
}

但是,执行代码会导致两个错误:

 reporters <- fromJSON(file=string)
 Error in readLines(file, warn = FALSE) : 'con' is not a connection
 reporters <- as.data.frame(t(sapply(reporters$results,rbind)))
 Error in reporters$results : object of type 'closure' is not subsettable

和string包含以下信息:

 List of 2
 $ validation: Named chr [1:12] "Ok" "0" "0" "" ...
 ..- attr(*, "names")= chr [1:12] "status.name" "status.value"       "status.category" "status.description" ...
 $ data      :'data.frame': 3 obs. of  35 variables:
 ..$ pfCode       : Factor w/ 1 level "H2": 1 1 1
 ..$ yr           : Factor w/ 1 level "2002": 1 1 1
 ..$ period       : Factor w/ 1 level "2002": 1 1 1
 ..$ periodDesc   : Factor w/ 1 level "2002": 1 1 1
 ..$ aggrLevel    : Factor w/ 1 level "0": 1 1 1
 ..$ IsLeaf       : Factor w/ 1 level "0": 1 1 1
 ..$ rgCode       : Factor w/ 3 levels "1","2","3": 1 2 3
 ..$ rgDesc       : Factor w/ 3 levels "Export","Import",..: 2 1 3
 ..$ rtCode       : Factor w/ 1 level "842": 1 1 1
 ..$ rtTitle      : Factor w/ 1 level "USA": 1 1 1
 ..$ rt3ISO       : Factor w/ 1 level "USA": 1 1 1
 ..$ ptCode       : Factor w/ 1 level "124": 1 1 1
 ..$ ptTitle      : Factor w/ 1 level "Canada": 1 1 1
 ..$ pt3ISO       : Factor w/ 1 level "CAN": 1 1 1
 ..$ ptCode2      : Factor w/ 0 levels: NA NA NA
 ..$ ptTitle2     : Factor w/ 1 level "": 1 1 1
 ..$ pt3ISO2      : Factor w/ 1 level "": 1 1 1
 ..$ cstCode      : Factor w/ 1 level "": 1 1 1
 ..$ cstDesc      : Factor w/ 1 level "": 1 1 1
 ..$ motCode      : Factor w/ 1 level "": 1 1 1
 ..$ motDesc      : Factor w/ 1 level "": 1 1 1
 ..$ cmdCode      : Factor w/ 1 level "TOTAL": 1 1 1
 ..$ cmdDescE     : Factor w/ 1 level "ALL COMMODITIES": 1 1 1
 ..$ qtCode       : Factor w/ 1 level "1": 1 1 1
 ..$ qtDesc       : Factor w/ 1 level "No Quantity": 1 1 1
 ..$ qtAltCode    : Factor w/ 0 levels: NA NA NA
 ..$ qtAltDesc    : Factor w/ 1 level "": 1 1 1
 ..$ TradeQuantity: Factor w/ 0 levels: NA NA NA
 ..$ AltQuantity  : Factor w/ 0 levels: NA NA NA
 ..$ NetWeight    : Factor w/ 0 levels: NA NA NA
 ..$ GrossWeight  : Factor w/ 0 levels: NA NA NA
 ..$ TradeValue   : Factor w/ 3 levels "160794797453",..: 3 1 2
 ..$ CIFValue     : Factor w/ 0 levels: NA NA NA
 ..$ FOBValue     : Factor w/ 0 levels: NA NA NA
 ..$ estCode      : Factor w/ 1 level "0": 1 1 1 

任何类型的帮助推荐并尊重良好的业力,

最好的问候,Sara

1 个答案:

答案 0 :(得分:0)

我认为字符串应该分配为:

    string <- "http://comtrade.un.org/data/cache/reporterAreas.json"

并在数据的函数请求结束时:

    data<-get.Comtrade(px = "HS", ps = "2002" , p = "124" , r = "842" , fmt = "json")