添加R代码的例外

时间:2016-07-18 16:41:24

标签: r exception dataframe

在SO用户的帮助下,我得到了以下正确运行的代码,该代码根据ISBN编号的向量从API获取有关该书的信息。在上一次迭代期间,代码应该将列表中的数据合并到一个data.frame。 不幸的是,有些ISBN不正确,在map_2df函数中它收到错误(因为检索到的列表不正确)。

如何为此类错误添加例外? 附:示例向量中的最后一个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 个答案:

答案 0 :(得分: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