0

This is a follow-up question to a question I posed earlier (Evaluating a function pointed to by a string in R) to make the problem and solution both more generic. Suppose I have the following:

   x <- 1:3  
   y <- 2
   foo <- function(x, y) {x^y}  
   a <- "foo"  
   b <- "x"  
   c <- "y"

I want to be able to evaluate the function foo using the strings defined by a, b, and c. Something like match.fun(a)(b, c), which I know is wrong, but will return

[1] 1 4 9

Or to make the question even more general, suppose

   x <- 1:3  
   y <- 2
   foo <- function(x, y) {x^y}  
   a <- "foo"  
   b <- "x, y"

How might match.fun be used to provide the same solution?

Any help is appreciated.

Peter Bonate
  • 75
  • 1
  • 6
  • R is a proper functional language that allows for metaprogramming to manipulate code. Language symbols are quite different than strings unlike in other more macro-like programming languages like SAS. You need to work with R code in parse-able chunks. Avoid putting arbitrary code in strings as much as possible. But if unavoidable, you can use the built in `parse()` functions which is basically how any string input at the console is turned into executable code. – MrFlick Feb 20 '21 at 03:21

1 Answers1

1

The issue is that 'b', 'c' are variables that store another variables 'x', 'y'. We need to get the value of those variables. For that get can be used, which will look up for the value in a recursive way

match.fun(a)(get(b), get(c))
#[1] 1 4 9
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Suppose b was b <- "x, y". How might that be converted using match.fun? – Peter Bonate Feb 19 '21 at 21:28
  • I answered for the question posted – akrun Feb 19 '21 at 21:31
  • I am trying to make the case as general as possible. The solution you provided answers the question directly posed. The online help for match.fun does not discuss any of this and I was trying to expand and generalize the solution as much as possible. – Peter Bonate Feb 19 '21 at 21:32
  • 1
    @PeterBonate Can you please update your post with all the possible cases you encounter. Each one of them is separately evaluated. If these are variables storing single variable, it is stored in memory stack. So, when we use `get`, it gets that data stored in that stack of memory. But, suppose if there are multiple variables, separated by `,`, each one of them are stored separately, we may need to split up that string with `strsplit` and then use `mget` or `get` – akrun Feb 19 '21 at 21:40