Skip to content

Instantly share code, notes, and snippets.

@viraltux
Last active September 10, 2015 07:41
Show Gist options
  • Select an option

  • Save viraltux/085e7e4d563522cfe9de to your computer and use it in GitHub Desktop.

Select an option

Save viraltux/085e7e4d563522cfe9de to your computer and use it in GitHub Desktop.
R function to that replaces 'key' tagged words (eg. $word) within a string with the value contained in the system by the local variable 'word'
SubSV <- function(string, env, key = '$'){
# Replaces 'key' tagged words (eg. $word) within a string with the value
# contained in the system by the local variable 'word'
#
# Args:
# string: string with 'key' tagged words.
# Returns:
# string with every 'key' tagged word replaced.
# Example:
# this <- 'by that'; SubSV('replace $this', environment())
while(grepl(paste('\\',key,sep=''),string)){
par <- gsub(paste('\\',key,sep=''),'',
regmatches(string,
regexpr(paste('\\',key,'\\w*',sep=''),string)))
regmatches(string,
regexpr(paste('\\',key,'\\w*',sep=''),
string)) <- get(par, envir = env)
}
return(string)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment