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