inject string at %(variable)s in R (Url pattern) -
i tryning build kind of rest full api comunicate r. got issue replacement of strings.
i've got url path as:
http://localhost:8000/rest/api/model/%(id)s/model_function
i need replace "%(id)s" model's id. function python stuff:
function(url, list(id=[id_value])
returning...
http://localhost:8000/rest/api/model/[id_value]/model_function
any tips around? implement string replacement:
substitute_url_args <- function(url, list_args){ replace_names <- paste("%(",names(list_args),")s", sep="")<br> <- 1 (i in 1:length(names(list_args))) { url <- sub(replace_names[i], list_args[[i]], url, fixed=true) } return(url) }
sure not elegant solution!
thanks in advance,
andré
try gsubfn
in gsubfn package:
library(gsubfn) substitute_url_args <- function(url, list_args) { gsubfn("%\\((.*?)\\)s", x = url, env = list_args) } # test s <- "http://localhost:8000/rest/api/model/%(id)s/model_function" l <- list(id = "[model_value]") substitute_url_args(s, l) ## [1] "http://localhost:8000/rest/api/model/[model_value]/model_function"
note if in control of , can specify backquotes surround substitutions easier:
substitute_url_args2 <- function(url, list_args) { gsubfn(x = url, env = list_args) } # test - l above ss <- "http://localhost:8000/rest/api/model/`id`/model_function" substitute_url_args2(ss, l) ## [1] "http://localhost:8000/rest/api/model/[model_value]/model_function"
note 2 if knew there 1 variable replace done using sub
this:
substitute_url_args3 <- function(url, list_args) { stopifnot(length(list_args) == 1) sub("%\\(.*?\\)s", list_args[[1]], url) } # test - s , l above substitute_url_args3(s, l) ## [1] "http://localhost:8000/rest/api/model/[model_value]/model_function"
Comments
Post a Comment