hol...@thebutlerfirm.com
unread,Jun 20, 2015, 4:55:01 AM6/20/15Sign in to reply to author
Sign in to forward
You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to sq...@googlegroups.com
Hey Gabor,
Thanks for your work, I had been looking for a good and reliable variable replacement function and found it in gsubfn. I'm a little confused by the scoping.
I could be mistaken but it looks like it's not taking parent.frame() as the default environment. So when I want to have gsubfn() inside a function, I have to explicitly define env = parent.frame(). E.g.,
library(gsubfn)
formals(gsubfn)$env #= parent.frame()
# default env
gsubAT <- function(string) {return(gsub("@","",gsubfn(x=string)))}
replaceTest <- function(variable) {return(gsubAT("The variable is $variable@"))}
replaceTest("test") #Error in eval(expr, envir, enclos) : object 'variable' not found
# env = environment()
gsubAT <- function(string) {return(gsub("@","",gsubfn(x=string,env=environment())))}
replaceTest <- function(variable) {return(gsubAT("The variable is $variable@"))}
replaceTest("test") #Error in eval(expr, envir, enclos) : object 'variable' not found
# env = parent.frame()
gsubAT <- function(string) {return(gsub("@","",gsubfn(x=string,env=parent.frame())))}
replaceTest <- function(variable) {return(gsubAT("The variable is $variable@"))}
replaceTest("test") #Works
# using replacement
gsubAT <- function(string,variables) {return(gsub("@","",gsubfn(x=string,replacement=variables)))}
replaceTest <- function(variables) {return(gsubAT("The variable is $variable@",variables=variables))}
replaceTest(list(variable="test")) #Works
I suppose the last version is best? Thanks.
Chris