Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a function or operator using a symbol?

Tags:

function

r

I would like to create a function with a symbol (for instance, ~), which works similarly to the "question mark" function.

like image 948
RockScience Avatar asked Feb 15 '23 19:02

RockScience


2 Answers

You can't do something as "bare" as ?foo without messing with the C code that defines the syntax of R. For example, you can't make [fnord be meaningful.

This comes from the syntax definition in gram.y in the R sources.

|   '~' expr %prec TILDE        { $$ = xxunary($1,$2); }
|   '?' expr            { $$ = xxunary($1,$2); }

|   expr ':'  expr          { $$ = xxbinary($2,$1,$3); }
|   expr '+'  expr          { $$ = xxbinary($2,$1,$3); }

The second line above defines the syntax for ?foo. What exactly are you trying to do?

like image 182
Spacedman Avatar answered Feb 18 '23 11:02

Spacedman


You can make functions and variables with arbitrary names, via use of the backtick `.

`~` <- `+`
y <- 5
x <- 10
y ~ x
# 15

I wouldn't mess with ~ though, unless you don't intend to do any statistical modelling....

like image 27
Hong Ooi Avatar answered Feb 18 '23 12:02

Hong Ooi