Last active
August 29, 2015 14:25
-
-
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")
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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