Site icon R-bloggers

Damn scoping in R

[This article was first published on binfalse » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Ok, R is very well-considered in certain respects, but there are also some things annoying me… This time it’s scoping…

Let’s have a look to the following code:

1
2
3
4
5
6
fun=function()
{
    if (runif(1) > .5)
        x = 1
    x
}

First it looks damn unspectacular. But wait, whats that:

1
2
3
4
5
> x=0
> fun()
[1] 1
> fun()
[1] 0

Taking a closer look to the function shows that the returned value is randomly chosen from local (runif(1) > .5) or global scope (runif(1) <= .5). So you can’t expect a result from this function. Nasty, especially while debugging external code, isn’t it? 🙂

1
2
> sum(sapply(1:10^6, function (null) fun()))/10^6
[1] 0.499681

So again my advise: Think about such specific features! This won’t happen in any sensible language…

To leave a comment for the author, please follow the link and comment on their blog: binfalse » R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.