[R] Remove " from a string

Marc Schwartz marc_schwartz at comcast.net
Fri Dec 8 15:13:55 CET 2006


On Fri, 2006-12-08 at 14:57 +0100, Katharina Vedovelli wrote:
> Hi all!
> 
> I have lots of functions called in the following pattern
> 'NameOfFunctionNumber' where the name always stays the same and the number
> varies from 1 to 98.
> Another function which I run in advance returns the number of the function
> which has to be called next.
> 
> Now I want to combine 'NameOfFunction' with the 'Number' returned so that i
> can call the desired function.
> I do this by:
> 
> x<-c("NameOfFunction",Number)
> z<-paste(x,collapse="")
> z
> 
> which returns
> 
> "NameOfFunctionNumber"
> 
> My Problem is that R doesn't recognise this as the name of my function
> because of the " at the beginning and the end.
> Is there a way of getting rid of those? Or does anybody know another way of
> solving this problem?
> 
> Thanks a lot for your help!
> Cheers,
> Katharina

It is not entirely clear what your ultimate goal is, thus there may be a
(much) better approach than calling functions in this manner. What do
the functions actually do and does the output vary based upon some
attribute (ie. the class) of the argument such that using R's typical
function dispatch method would be more suitable.

However, to address the specific question, at least two options:

 NameOfFunction21 <- function(x) x^2

> eval(call(paste("NameOfFunction", 21, sep = ""),  21))
[1] 441

> do.call(paste("NameOfFunction", 21, sep = ""),  list(21))
[1] 441

In both cases, the result is to evaluate the function call, with 21 as
the argument.  See ?call, ?eval and ?do.call for more information.

HTH,

Marc Schwartz




More information about the R-help mailing list