Reputation: 486
I'm trying to make a script to run through a list of ids to apply to an API call so that I can create a data.frame of results, where each result returned for each id called is a row.
library(jsonlite)
ids <- c("101","102","103")
baseURL <- "http://api.example.com/query_json.ashx?m=Details&Id="
for (i in ids) { details <- lapply((paste(baseURL,i, sep="")), fromJSON) }
My problem is that it iterates through each id but then returns only the result from the last one (103). It's obvious there is quite a basic solution, but I'm missing it.
Upvotes: 1
Views: 62
Reputation: 486
Thanks all, both suggestions worked.
Because the resulting fromJSON
R list was nested, I needed to adapt my code further so that the eventual data frame was properly structured.
library(jsonlite)
ids <- c("101","102","103")
nids <- length(ids)
baseURL <- "http://api.example.com/query_json.ashx?m=Details&Id="
details <- c()
for (i in ids) {
details <- lapply(ids, function(id) fromJSON(paste(baseURL,id, sep="")))
}
details <- data.frame(matrix(unlist(details), nrow=nids, byrow=T))
Upvotes: 0
Reputation: 1127
You could try sth like that
ids <- c("101","102","103")
baseURL <- "http://api.example.com/query_json.ashx?m=Details&Id="
details <- c()
for (i in ids) {
details[i] <- lapply((paste(baseURL,i, sep="")), fromJSON)
}
df <- data.frame(details, stringsAsFactors=FALSE)
First you put the results into vector and then create the data frame.
Upvotes: 1