Skip to content

Instantly share code, notes, and snippets.

@datalove
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save datalove/225879b7ef0ed2662e63 to your computer and use it in GitHub Desktop.
Save datalove/225879b7ef0ed2662e63 to your computer and use it in GitHub Desktop.
In-place string substitution in R. Example: s("my name is $x and time is $y")
s <- function(str) {
require(stringr)
require(magrittr)
# helper functions
get_vars <- function(str) str %>% str_extract_all("\\$[a-zA-Z0-9_\\.]+") %>% unlist %>% str_replace_all("\\$","")
eval_var <- function(var) eval(parse(text = var)))
add_token <- function(var) paste0("\\$", var)
# replace a given var with its value in a string
replace_var <- function(str,var) str %>% str_replace_all(add_token(var), eval_var(var))
vars <- get_vars(str)
# replace each variable with its value
for(i in seq_along(vars))
str <- replace_var(str, vars[i])
str # return updated string
}
rows <- 22
duration.secs <- 60
s("($rows rows, $duration.secs s)")
# [1] "(22 rows, 60 s)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment