Cyrus' New Completely Useless Blog

Hey R (#rstats), WTF?

So I regularly find myself thinking "what where the designers of R thinking?". For today's example, consider the following contrived example. Say I've got the following function definition:

foo <- function(x) {
    cat("Hey, I've got a", x, "\n")

So far so good. I can do:

> foo("moose")
Hey, I've got a moose 

Ok, but now I want to default the argument, but I don't want to just say x = "moose" as I might want to use the same string elsewhere, only write it once, etcd... So I do:

x <- moose

foo <- function(x=x) {
    cat("Hey, I've got a", x, "\n")

and if I do: > foo("gazelle") Hey, I've got a gazelle

It looks like everything is OK. Until I go to do:

> foo()
Error in cat("Hey, I've got a", x, "\n") : 
  promise already under evaluation: recursive default argument reference or earlier problems?

WTF? Of course I want the value of x I defined above and of course setting the value of x to the currently-being-defined value makes n sense. Who designed the scoping rules here?