Wednesday, October 15, 2014

R's quirky nested assignment

R has some quirky features that I think exist to serve its functional paradigm.  One of the oddest is what I know only as nested assignment, as demonstrated in this function for the Collatz sequence:

collatz <- function(x) {
  cseq <- c(x)
  while (x>1) cseq <- c(cseq, x<-ifelse(x%%2<1, x/2, 3*x+1))
  cseq
}

Here in the call to combine--c--we've also assigned x a new value.  The really odd thing about this is that most general-purpose non-lisp style languages use the equal sign = as the assignment operator.  In function calls the assignment operator is slightly different, where k=v usually means "set the argument named k to the value v," and that's exactly what the equal sign in R's function calls also mean.  But since R uses a little ASCII arrow <- for the assignment operator, it is still free to make assignments outside the scope of the called function within the argument list of the called function!  Because R is a functional language, most function calls must be assigned to something.  In this sense assignments within function calls are nested.  Kinda weird, but it saves lines of code and is probably suited to a functional style where one might (tastefully) chain together a couple (anonymous) functions.

The next post will look at the functions behind R's operators and how to use them with sapply and friends.  As it turns the assignment operator is a function!  The subset operator is also a function and this enables some really elegant solutions for data management using R's base functions.

No comments:

Post a Comment