Build an URL with parameters in R

混江龙づ霸主 提交于 2021-02-07 12:17:22

问题


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)

What I like about the code that I have now, is that I can easily change parameter values and rebuild the URL.

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

But loading the data.table library, only to build an url, just doesn't feel right. Is there a better to do this?


回答1:


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) }

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


来源:https://stackoverflow.com/questions/53350738/build-an-url-with-parameters-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!