1 + 1 = 3, the proof in R

December 1, 2012

(This article was first published on jean-robert.github.com, and kindly contributed to R-bloggers)

Discussing with some friends the other day, one of them mentioned a supposedly famous quote from Einstein saying that 1 + 1 = 3. Despite my best efforts, Google couldn’t find that particular quote. Anyway, we were trying to understand how could have Einstein come up with that. Our answer was that the proposition “1 + 1 = 3” is true when ”+” corresponds to the concatenate operator and ”=” corresponds to the equality between a base-2 number and a base-10 number.

Jokes aside, this is a good opportunity to remember how nice R is when it comes to overriding primitive operators. Indeed, the ”+” operator in R works well with many various types (numeric, vector, matrices, …), but you can also make it work the way you want. In our case, we want the ”+” operator to concatenate and compute in base 2. This can be done as follow:

"+" <- function(e1, e2) {
    sum(c(e1 * 2, e2))

A pitfall to avoid is to define your function like this:

"+" <- function(e1, e2) {
    e1 * 2 + e2

This won’t work since you are defining ”+” using ”+”… Hence an infinite recursion that R will quickly remind you of. Instead, using the sum function (another primitive) allows you to use the correct ”+” when suming up.

If you use the first function defined above, you get the answer that everyone expected: 1+1=3. Even better, you can write any number in base 2, like 1+1+0+1 and it will return the base-10 answer: 13.

1 + 1
# 3
1 + 1 + 0 + 1
# 13

In a more generic way, you can define any operator you like using ”%”:

"%foo%" <- function(e1, e2) {
    sum(c(e1 * 3, e2))

Oh, and just in case, do not forget to rm('+')

To leave a comment for the author, please follow the link and comment on their blog: jean-robert.github.com.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)