2017-07-22 3 views
1

私はAPIからいくつかのデータを取得しようとしているすべての単一のデータフレームに投げる。私は引っ張っているURLに変数を入れようとしていて、それをループして54個のキーからデータを引き出します。ここで私はこれまでにノートを持っています。APIクエリループ

library("jsonlite") 
library("httr") 
library("lubridate") 
options(stringsAsFactors = FALSE) 
url <- "http://api.kuroganehammer.com" 

### This gets me a list of 58 observations, I want to use this list to 
### pull data for each using an API 

raw.characters <- GET(url = url, path = "api/characters") 
## Convert the results from unicode to a JSON 
text.raw.characters <- rawToChar(raw.characters$content) 
## Convert the JSON into an R object. Check the class of the object after 
## it's retrieved and reformat appropriately 
characters <- fromJSON(text.raw.characters) 
class(characters) 

## This pulls data for an individual character. I want to get one of 
## these for all 58 characters by looping this and replacing the 1 in the 
## URL path for every number through 58. 
raw.bayonetta <- GET(url = url, path = "api/characters/1/detailedmoves") 
text.raw.bayonetta <- rawToChar(raw.bayonetta$content) 
bayonetta <- fromJSON(text.raw.bayonetta) 

## This is the function I tried to create, but I get a lexical error when 
## I call it, and I have no idea how to loop it. 
move.pull <- function(x) { 
    char.x <- x 
    raw.x <- GET(url = url, path = cat("api/characters/",char.x,"/detailedmoves", sep = "")) 
    text.raw.x <- rawToChar(raw.x$content) 
    char.moves.x <- fromJSON(text.raw.x) 
    char.moves.x$id <- x 
    return(char.moves.x) 
} 

答えて

1

本の最初の部分:

library(jsonlite) 
library(httr) 
library(lubridate) 
library(tidyverse) 

base_url <- "http://api.kuroganehammer.com" 

res <- GET(url = base_url, path = "api/characters") 
content(res, as="text", encoding="UTF-8") %>% 
    fromJSON(flatten=TRUE) %>% 
    as_tibble() -> chars 

はあなたの文字のデータフレームを取得します。

この:

pb <- progress_estimated(length(chars$id)) 
map_df(chars$id, ~{ 

    pb$tick()$print() 

    Sys.sleep(sample(seq(0.5, 2.5, 0.5), 1)) # be kind to the free API 

    res <- GET(url = base_url, path = sprintf("api/characters/%s/detailedmoves", .x)) 

    content(res, as="text", encoding="UTF-8") %>% 
    fromJSON(flatten=TRUE) %>% 
    as_tibble() 

}, .id = "id") -> moves 

はあなたにすべての「移動」のデータフレームを取得し、文字の「ID」を追加します。プログレスバーも無料で入手できます。

必要に応じてleft_join()またはグループ&のいずれかを指定すると、移動データが別のリストネスト列にネストされます。あなたがそれを始めるにはmap()map_df()を使うことができます。

時間のポーズコードを残します。無料のAPIなので、サイトのDoSを避ける​​ために一時停止時間を長くする必要があります。

+0

これは素晴らしく、完璧に機能しました。パイプ演算子とmap_dfを動作させるために、dplyrとpurrrもロードしました。時間のポーズコードについてのヒントをありがとう、私はそれを行うことを考えたことはありません! – Oct

+0

'tidyverse'はあなたにdplyr&purrrを与えます – hrbrmstr

+0

ああ私は、私のライブラリにそれを持っていないと思う。 – Oct

関連する問題