2017-08-07 51 views
0

我的代碼如下設計用於通過API端點驗證數據(及其元數據),並將所有元數據返回到數據框。我想要創建一個嵌套的函數,爲另一個具有相同身份驗證的API端點重複這個相同的過程,並將第二個端點的結果附加到第一個端點,並將其結果添加到一個數據框中(它們都具有相同的數據結構和標頭)。我不知道在這個過程中,我應該把link_to_endpoint2,怎麼辦嵌套,結果追加等嵌套函數用於檢索R中的多個URL(帶身份驗證)中的數據

get_data <- function(uid, credentials, root_url) { 

    cookie <- credentials$cookie 
    token <- credentials$token 

    start_time <- Sys.time() 
    print (start_time) 
    url <- paste0(root_url, 'link_to_endpoint1', uid) 
    resp <- httr::GET(url, 
        httr::add_headers(.headers = c(`Content-Type` = "application/json", 
                Cookie = cookie, `X-CSRF-Token` = token)), 
        body = body, 
        encode = "json") 

    httr::warn_for_status(resp) 
    resources <- httr::content(resp) 
    access_check <- resources$result$error 
    assertthat::assert_that(is.null(access_check), 
          msg = 'Access denied') 

    resources <- resources$result[[1]]$resources 
    res_ids <- purrr::map_chr(resources, 'id') 
    res_urls <- purrr::map_chr(resources, 'url') 
    res_desc <- purrr::map_chr(resources, 'description') 
    res_format <- purrr::map_chr(resources, 'format') 
    res_rclass <- purrr::map_chr(resources, 'data_classification_of_file') 
    res_rtype <- purrr::map_chr(resources, 'mimetype') 
    res_rname <- purrr::map_chr(resources, 'name') 
    out <- data.frame(res_ids, 
        res_urls, 
        res_desc, 
        res_format, 
        res_rclass, 
        res_rtype, 
        res_rname, 
        stringsAsFactors = FALSE) 
    out$id <- uid 
    end_time <- Sys.time() 
    print (end_time) 
    process_time <- (end_time - start_time) 
    print(process_time) 
    return(out) 
} 
+0

嗨蘇西,如果我的解決方案爲你工作,請考慮通過點擊左邊的複選標記接受它作爲答案。這讓我知道它對你有用,社區知道它也起作用。 – CPak

回答

0

你必須要測試這個解決辦法,但你可以嘗試

這些線路更改爲

# Old line 
New line 

# get_data <- function(uid, credentials, root_url) { 
get_data <- function(uid, credentials, root_url, link) { 

# url <- paste0(root_url, 'link_to_endpoint1', uid) 
url <- paste0(root_url, link, uid) 

然後,你可以調用這個函數(假設你已經加載purrr

links <- c('link_to_endpoint1', 'link_to_endpoint2') 
desired <- map_df(links, ~get_data(uid, credentials, root_url, .x)) 
相關問題