4

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?

1
  • You could 'collapse' the result of parse_url to what you expect it to. x <- list(a = "1", a = "2", b = "val"); lapply(split(x, as.factor(names(x))), function(y) do.call("c", y)) . Commented Mar 12, 2014 at 9:06

1 Answer 1

2

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)))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.