R Tricks – Macros and Conditional Execution in R


1 Use Macros in R

Problem

You want to use C-like macros, such as “#define” in R.

Solution

Use “defmacro” in {gtools} pacakge.

> library(gtools);
> mul<-defmacro(a, b, expr={a*b});
> mul(2,3);
[1] 6
> CONST_PI<-defmacro(0, expr={3.1415926});#0 is useless here
> print(CONST_PI(0));
[1] 3.141593

http://cran.r-project.org/web/packages/gtools/index.html
https://stat.ethz.ch/pipermail/r-help/2007-April/130015.html

2 Conditional Execution

Problem

You want to use C-like macros, such as “#include” and C-like conditional compiling macros, such as “#if, #elif, #else, #endif“, in R.

Solution

There is no preprocessor for R, but you can use keyword “source” and “if/else” for conditional execution.

Debug<-TRUE;
if(Debug)
{source("C:/Debug.r");}
else
{source("C:/NoDebug.r");}
#C:\Debug.r
print("Debug");
#C:\NoDebug.r
print("NoDebug");
Advertisements
This entry was posted in programming, r. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s