Wiki: R
GitHub: edit | view

Check out R Golfing Tips on CGSE


R, as a statistical language, has tons of builtins and functions that are very useful when golfing. Here are some of them:

rle                # Run Length Encoding
gl                 # Generate factors by specifying the pattern of their levels
letters            # 'a','b','c'...
LETTERS            # 'A','B','C'...          # 'Jan','Feb','Mar'...         # 'January','February','March'...
T                  # TRUE
F                  # FALSE

T and F are very powerful because you don't need to initialize a variable to 1 or 0 at the start of your code.


We can define short aliases for functions using backticks for two arguments using primitive operators:

x+y                # paste(x,y)

(There is a way to define a short alias for functions with 3 or more arguments)


Some examples of using coercion to avoid using long functions:



outer function

outer is a fairly strong function. It takes the two arrays and applies a vectorized function. It acts like Julia's array manipulation feature:


# [1 2 3; 2 4 6; 3 6 9]

In R:


# 1 2 3 2 4 6 3 6 9

You can place any operator or function (with quotes around it) in the third argument for outer.

outer(X,Y,"*") can also be rewritten as:

X%*%t(Y)           # %*% is matrix vector multiplication

Or even better:


rep() alternatives

Even though rep() is already fairly short, we can save a few more bytes by using : and vector recycling.

Repeating n zeroes (n>0) - !1:n or 0*1:n instead of rep(0,n)

Repeating n ones - !!1:n instead of rep(1,n)

Repeating x n times - x+!1:n instead of rep(x,n)

Using modular arithmetic to avoid each args in rep

There aren't too many uses of this, but when you encounter one, you will probably need some creativity to come up with some "formula".

Generating the vector c(-1,-1,-1,0,0,0,1,1,1) is easily done with rep(-1:3,e=3), but you can use modular arithmetic to save bytes:


Random Tips