使用 R 中的参数构建 URL [英] Build an URL with parameters in R
问题描述
在 R 中使用参数构建请求 URL 的最佳方法是什么?到目前为止,我想出了这个:
What is the best way to build a request URL with parameters in R? Thus far I came up with this:
library(magrittr)
library(httr)
library(data.table)
url <- list(hostname = "geo.stat.fi/geoserver/vaestoalue/wfs",
scheme = "https",
query = list(service = "WFS",
version = "2.0.0",
request = "GetFeature",
typename = "vaestoalue:kunta_vaki2017",
outputFormat = "application/json")) %>%
setattr("class","url")
request <- build_url(url)
我喜欢我现在拥有的代码的一点是,我可以轻松地更改参数值并重建 URL.
What I like about the code that I have now, is that I can easily change parameter values and rebuild the URL.
此外,生成的 url 是正确的 html 编码:
Also, the resulting url is properly html encoded:
https://geo.stat.fi/geoserver/vaestoalue/wfs/?service=WFS&version=2.0.0&request=GetFeature&typename=vaestoalue%3Akunta_vaki2017&outputFormat=application%2Fjson
但是加载data.table库,只是为了建一个url,感觉不太对.有没有更好的方法?
But loading the data.table library, only to build an url, just doesn't feel right. Is there a better to do this?
推荐答案
您绝对不需要 data.table
来构建 URL.正如 José 所指出的,它被加载以使用您可以模仿的单一便利功能:
You absolutely don't need data.table
to build URLs. As José noted, it was loaded to use a single convenience function you can just mimic with:
set_class <- function(o, v) { class(o) <- v ; invisible(o) }
此外,除非目标是有一个 URL 而不是从网站读取数据,否则你也可以只使用 httr
动词:
Also, unless the goal is to have a URL vs just read data from a site, you can also just use httr
verbs:
httr::GET(
url = "https://geo.stat.fi/geoserver/vaestoalue/wfs",
query = list(
service = "WFS",
version = "2.0.0",
request = "GetFeature",
typename = "vaestoalue:kunta_vaki2017",
outputFormat = "application/json"
)
) -> res
dat <- httr::content(res)
str(dat, 1)
## List of 5
## $ type : chr "FeatureCollection"
## $ totalFeatures: int 311
## $ features :List of 311
## $ crs :List of 2
## $ bbox :List of 4
这篇关于使用 R 中的参数构建 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!