简体   繁体   中英

Access the if statement via base::if() in R

I am coding in R and due to stability purposes when I have to deploy something, I call every function with the syntax package::function(arguments) just to avoid conflicts that as you know may happen when using a lot of packages. It helped me a lot over the years.

I know that if is a reserved word so technically speaking it is impossible (or at least it should be in my knowledge) for someone to define an object and name it if .

I am also aware that it belongs to control flow statement (which I think are a different "thing") and due to the previous consideration I am also aware that the following questions might be useless. My pure technical doubts are:

  1. Why if I embrace it in back-ticks the function class returns "function" as a result?
  2. Why without back-ticks I get an error? and last but most important
  3. Why I am unable to access it via the usual base::if() syntax?

As I said, most likely useless questions but at this point I am curious about the details underneath it.

> class(if)
Error: unexpected ')' in "class(if)"

> class(`if`)
[1] "function"

> base::if(T) T
Error: unexpected 'if' in "base::if"
> if(T) T
[1] TRUE
> base::if(`T`) T
Error: unexpected 'if' in "base::if"

if -with-backticks actually returns .Primitive("if")

The R language definition section on "Internal vs Primitive" specifies that .Primitive objects include

“Special functions” which really are language elements, but implemented as primitive functions:

{ ( if for while repeat break next return function quote switch

The reason that a naked "if" without backticks or base::if don't work is that the "language elements" above are treated as special cases by R's parser. Once you have typed base:: , R's parser expects the next symbol to be a regular symbol that can be looked up in the base namespace. base::if , base::for , and base::( all return errors because R does not expect these special elements to occur at this position in the input stream ; they are syntactically incorrect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM