0

Is it possible to assign subtraction (or division) in R as object and to call it? So that following example produce -1

a <- 1
b <- 2

method <- "-"
a method b
# Wanted result -1

method <- "/"
a method b
# Wanted result 0.5

Why I need this
I want to set function parameter to either - or /. Something like that:

dummyF <- function(a, b, method) {
    a get(method) b
}
pogibas
  • 27,303
  • 19
  • 84
  • 117
  • 1
    Would `dummyF <- function(a, b, method) { txt = paste(a, method, b); eval(parse(text=txt)) }` suit your needs? – tblznbits Apr 18 '16 at 16:50
  • 1
    If you only have two possible methods, you might want to hard-code them and then make selection a TRUE/FALSE option, like `function(a, b, do_plus) (if (do_plus) \`+\` else \`/\`)(a, b)` – Frank Apr 18 '16 at 17:11

2 Answers2

8

You can use backticks and then call the function using normal function notation, not infix notation:

foo <- `-`
foo(1,2)

An example with them in a list:

l <- list(add = `+`,subtract = `-`)
> l[["add"]](1,2)
[1] 3
> l[["subtract"]](1,2)
[1] -1
joran
  • 169,992
  • 32
  • 429
  • 468
6

We can use do.call

method <- "-"
do.call(method, list(a,b))
#[1] -1

method <- "/"
do.call(method, list(a,b))
#[1] 0.5
akrun
  • 874,273
  • 37
  • 540
  • 662