【发布时间】:2020-03-12 16:30:08
【问题描述】:
我创建了一个从 API 获取数据的网络抓取功能。我将df 列传递给网络抓取函数中的函数参数之一。我遇到的问题是 URL 在其中一个参数中最多占用 500 个数字,而我的 df 有 2000 行。
如何将行拆分为 500 以便将值传递给函数?
我创建了一个非常基本的表示,它显示了我想要做的工作流程。我想将拆分的 df 列传递给 parse 函数。我猜我需要用map_dfr 包装JSON 解析
library(tidyverse)
sample_df <- tibble(id = 1:20,
col_2 = rnorm(1:20))
# parse function
parse_people <- function(ids = c("1", "10"), argument_2 = NULL){
# Fake Base Url
base_url <- "https://www.thisisafakeurl.com/api/people?Ids="
# fix query parameters to collapse Ids to pass to URL
ids<- stringr::str_c(ids, collapse = ",")
url <- glue::glue("{base_url}{ids}")
# Get URL
resp <- httr::GET(url)
# Save Response in JSON Format
out <- httr::content(resp, as = "text", encoding = "UTF-8")
# Read into JSON format.
jsonlite::fromJSON(out, simplifyDataFrame = TRUE, flatten = TRUE)
}
sample_parse <- parse_people(sample_df$id)
我想我可能需要创建 2 个函数。 1 个解析数据的函数,以及一个基于拆分使用 map_dfr 的函数。
类似:
# Split ID's from DF here. I want blocks of 500 rows to pass below
# Map Split ID's over parse_people
ids %>%
map_dfr(parse_people)
【问题讨论】:
-
你能检查一下我的解决方案吗