On 22/09/2014 9:16 AM, Daniel Fuka wrote:> Howdy,
>
> I have searched the lists and can not seem to find a solution to my
> problem. I need to be able to dynamically modify a string inside a
> function to build a new function. "sub" replaces with a quoted
> string... and "parse" of "sub" returns expression...
How can I get an
> unquoted string from a regex to stick into a "body" of a
function?
It's possible to do what you want, though you don't want to be using
parse(), you can just edit the language expression that body(fsong)
gives you, and assign it back. But that's a messy way to solve your
problem.
Why not create a new function containing the new string? e.g.
makefsong <- function(name = "fuka") {
line1 <- paste("my name is", name)
function(x) {
song <- paste(line1, x)
return(song)
}
}
f1 <- makefsong()
f1("I live on the second floor")
f2 <- makefsong("muka")
f2("I live on the second floor")
Duncan Murdoch
>
> Thanks for your help!
> dan
>
> # Original Function
> fsong=function(x){
> song=paste("my name is fuka,",x)
> return(song)
> }
> fsong("I live on the second floor")
> #
> # Copy and modify using "sub" returns quoted string with escaped
quotes
> # internally... as expected.. which can not be evaluated.
> nsong=fsong
> body(nsong)[[grep("fuka",body(nsong))]]>
sub("fuka","muka",list(body(fsong)[[grep("fuka",body(fsong))]]))
>
> nsong("I live on the second floor") # broken
>
> #
> # Copy and modify with "parse" of "sub", returns
expression.. but
> without quotes,
> # o getting closer.
> #
> nsong=fsong
> body(nsong)[[grep("fuka",body(nsong))]]>
parse(text=sub("fuka","muka",list(body(fsong)[[grep("fuka",body(fsong))]])))
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.