2016-07-18 82 views
1

在SO用戶的幫助下,我得到了以下正常工作的代碼,可以從API獲取有關基於ISBN編號向量的書籍的信息。在上次迭代期間,代碼應該將列表中的數據合併到一個data.frame中。 不幸的是,一些ISBN不正確,在map_2df函數期間它收到錯誤(因爲檢索到的列表不正確)。向R代碼添加異常

如何爲這些錯誤添加異常? P.S.在例如向量的最後一個ISBN是不正確

library(purrr) 

isbns<- c("9785170857098", "9785170840601", "9785170916900", "9785170640966", "9785669656714") 
# Paste is vectorized, so make a list of URLs all at once. 
# `httr` can make a URL out of a list of named parameters, if it's more convenient. 
results <- paste0("http://www.knigoed.info/api/Prices?code=", 
        isbns, 
        "&sortPrice=DESC&country=RU") %>% 
     # Iterate over vector of URLs, using fromJSON to pull and parse the request. 
     # map, like lapply, will put the results into a list. 
     map(jsonlite::fromJSON, flatten = FALSE) 

# Grab "prices" element of each top-level list element 
results %>% map('prices') %>% 
     # Iterate in parallel (like mapply/Map) over prices and isbns, making a data.frame of 
     # each. map2_df will coerce the resulting list of data.frames to a single data.frame. 
     map2_df(isbns, ~data.frame(isbn = .y, .x, stringsAsFactors = FALSE, check.rows=FALSE)) %>% 
     # assign data frame to analyzedData 
     {.} -> analyzedData 
+1

看看'?try' - 你可以檢查代碼是如何評估的,然後使用if/else語句來返回你想要的。 – dayne

回答

0

從Purrr庫,請safely()函數來創建安全功能,讓您捕捉到的結果和錯誤,同時將完成您擁有正確的ISBN任務。

safe_map <- safely(map) 

# Grab "prices" element of each top-level list element 
analyzedData <- results %>% 
        safe_map(.f = ~ {rep_len <- length(.x$prices$priceValue); 
            data.frame(isbn    = rep(.x$code, rep_len), 
               priceValue  = .x$prices$priceValue, 
               stringsAsFactors = FALSE, 
               check.rows  =FALSE)}) 

str(analyzedData) 

res <- do.call(rbind, analyzedData[["result"]]) 
errs <- do.call(rbind, as.list(analyzedData[["error"]])) 
library("dplyr") 
isbn_prices <- res %>% 
       group_by(isbn) %>% 
       filter(isbn %in% isbns) 

> isbn_prices 
Source: local data frame [15 x 2] 
Groups: isbn [4] 

      isbn priceValue 
      (chr)  (dbl) 
1 9785170857098  1119 
2 9785170857098  992 
3 9785170857098  899 
4 9785170857098  899 
5 9785170857098  899 
6 9785170857098  899 
7 9785170857098  712 
8 9785170857098  449 
9 9785170840601  535 
10 9785170840601  451 
11 9785170840601  445 
12 9785170840601  392 
13 9785170916900  662 
14 9785170916900  199 
15 9785170640966  445 
> errs 
NULL