[R] Converting a string

jim holtman jholtman at gmail.com
Mon Oct 29 23:16:26 CET 2007


Here is a way of using parse and eval that was previously mentioned.
It works with constants, variable names or expressions:

> myFunc <- function(arg1, arg2) arg1+arg2
>
> x <- 20
> y <- 10
> myFunc(x,y)
[1] 30
>
> tempstr <- 'x,y'
> # split the string
> args <- strsplit(tempstr, ',')
> # parse and eval the characters
> myFunc(eval(parse(text=args[[1]][1])), eval(parse(text=args[[1]][2])))
[1] 30
>
> tempstr <- '10,20'
> # split the string
> args <- strsplit(tempstr, ',')
> # parse and eval the characters
> myFunc(eval(parse(text=args[[1]][1])), eval(parse(text=args[[1]][2])))
[1] 30
>
> tempstr <- '2 * 5, 40 / 2'  #works with expressions
> # split the string
> args <- strsplit(tempstr, ',')
> # parse and eval the characters
> myFunc(eval(parse(text=args[[1]][1])), eval(parse(text=args[[1]][2])))
[1] 30
>
>


On 10/29/07, Gang Chen <gangchen at mail.nih.gov> wrote:
> Thanks for the help.
>
> One case is like this: With function MyFunc(Argument1,
> Argument2, ...) I have the first two arguments defined as one
> variable "tempstr", a string of characters, like
>
> tempstr <- "Argument1, Argument2"
>
> The question is how I can feed tempstr into MyFunc to make it
> executable?
>
> Gang
>
> On Oct 29, 2007, at 5:42 PM, jim holtman wrote:
>
> > Can you provide an example of your input and what you expect the
> > output to be.  You can always use 'as.numeric'.
> >
> > On 10/29/07, Gang Chen <gangchen at mail.nih.gov> wrote:
> >> This must be very simple, but I'm stuck. I have a command line in R
> >> defined as a variable of a string of characters. How can I convert
> >> the variable so that I can execute it in R?
> >>
> >> Really appreciate any help,
> >> Gang
>


-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list