Some tips:
- In R, it's recommended to use
<- over =. For golfing, the
opposite holds since = is shorter...
If you call a function more than once, it is often beneficial to
define a short alias for it:
as.numeric(x)+as.numeric(y)
a=as.numeric;a(x)+a(y)
Partial matching can be your friend, especially when functions
return lists which you only need one item of. Compare
rle(x)$lengths to rle(x)$l
Many challenges require you to read input. scan is often a good fit for this (the user ends the input by entring an empty line).
scan() # reads numbers into a vector
scan(,'') # reads strings into a vector
Coercion can be useful. t=1 is much shorter than t=TRUE. Alternatively, switch can save you precious characters as well, but you'll want to use 1,2 rather than 0,1.
if(length(x)) {} # TRUE if length != 0
sum(x<3) # Adds all the TRUE:s (count TRUE)
If a function computes something complicated and you need various other types of calculations based on the same core value, it is often beneficial to either: a) break it up into smaller functions, b) return all the results you need as a list, or c) have it return different types of values depending on an argument to the function.
As in any language, know it well - R has thousands of functions, there is probably some that can solve the problem in very few characters - the trick is to know which ones!
Some obscure but useful functions:
sequence
diff
rle
embed
gl - Like rep(seq(),each=...) but returns a factor
Some built-in data sets and symbols:
letters # 'a','b','c'...
LETTERS # 'A','B','C'...
month.abb # 'Jan','Feb'...
month.name # 'January','Feburary'...
T # TRUE
F # FALSE
pi # 3.14...