Skip to content

"if" function in pure R?

4 messages · Jiefei Wang, Alexandre Courtiol, Stepan

#
Hi all,

Could anyone refer to me to a good source to learn how to program a simple
control-flow construct* in R, or provide me with a simple example?

Control-flow constructs are programmed as primitives, but I would like to
be able to do that (if possible) in pure R.

The general context is that those functions are a mystery to me. The
motivating example is that I would like to create a function that behave
similarly to base::`if` with an extra argument to the function (e.g. to
include an error rate on the condition).

Many thanks,

Alex

* control-flow constructs are functions such as if, for, while... that
allow for call of the form fn(x) expr to work (see ?Control).
#
Hi Alexandre,

I'm not an R expert so this is only my personal thought:

I don't think you can achieve what you want exactly. A possible solution
would be defining a binary operator %*%, where you can replace the asterisk
with any function name you want. The function %*% is special since it has
two arguments, left operand and right operand respectively. You then
can call the `substitute` function to get its function arguments in an
expression format and proceed to do what you want. Here is an example to
show the idea.

*Code:*

`%myOperator%` <- function(x, y) {
  x = substitute(x)
  y = substitute(y)
  return(list(x, y))
}


myIf(i == 1, arg1) %myOperator% {
  doSomeThing
}


*Results:*

[[1]]
myIf(i == 1, arg1)

[[2]]
{
    doSomeThing
}

I hope that helps.

Best,
Jiefei

On Sun, May 26, 2019 at 4:45 AM Alexandre Courtiol <
alexandre.courtiol at gmail.com> wrote:

            

  
  
#
Thanks a lot Jiefei,

I had thought of defining a binary operator (inspired by pipes) or simply
using an additional condition in the if() calls [e.g. if(foo & fn(bar))
doSomeThing; with fn(bar) returning a logical], but both are workaround
that I do not find as elegant as a proper control-flow construct.

Thus two questions remain:
- is it possible to create a control-flow construct in pure R?
- if yes, how?

Anyone with more insights?
Thanks
On Mon, 27 May 2019 at 04:27, King Jiefei <szwjf08 at gmail.com> wrote:

            

  
    
#
Hello Alexandre,

there are two sides of your question it seems to me:

- there is no possibility to extend the R parser with new syntax. The R 
parser knows to internally "rewrite"(*) things such as

if (a>b) print(1) else print(2)

into

`if`(a>b, print(1), print(2))

The parser has a fixed set of functions that get some special treatment 
like this.

- there is possibility to implement control flow constructs thanks to 
the lazy evaluation of arguments. An example of such function is ifelse 
from base.

Best,
Stepan

(*) "rewrite" is illustrative, the exact internal working of this is not 
important for this discussion
On 27/05/2019 08:16, Alexandre Courtiol wrote: