Question

Is there a straightforward way to parse and build URL query string with multiple value parameters in R ?

I would expect something like

myqueryString <- parse_url("http://www.mysite.com/?a=1&a=2&b=val")$query
myqueryString
  $a
  [1] 1 2
  $b
  [1] "val"

and

urlElements <- list(scheme="http",path="www.mysite.com/",query=list(a=c(1,2),b="val"))
setattr(urlElements,"class","url")
build_url(urlElements)
  [1] "http://www.mysite.com/?a=1&a=2&b=val"

However httr gives

parse_url("http://www.mysite.com/?a=1&a=2&b=val")$query
 $a
 [1] "1"

 $a
 [1] "2"

 $b
 [1] "val"

and

builtURL <- build_url(urlElements)
builtURL
   [1] "http:///www.mysite.com/?a=c%281%2C%202%29&b=val"

This latest URL can be reprocessed

parse_url(builtURL)$query
 $a
 [1] "c(1, 2)"

 $b
 [1] "val"

I understand that I can use parse() + eval() to get a back but it looks fairly unsafe to eval code that can be freely dumped to an URL. Any suggestions?

Was it helpful?

Solution

See if these work to convert between those two argument list formats:

mergeUrlArgs <- function(x) sapply(unique(names(x)), function(z) unlist(x[names(x) == z], use.names=FALSE), simplify=FALSE)

expandUrlArgs <- function(x) structure(do.call(c, lapply(x, function(z) as.list(z))), names=rep(names(x), sapply(x, length)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top