Damn scoping in R

February 17, 2011
By

(This article was first published on binfalse ยป R, and kindly contributed to R-bloggers)

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 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...

Tags: , , , , ,

Comments are closed.

Sponsors

Mango solutions



RStudio homepage



Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training



http://www.eoda.de







ODSC

ODSC

CRC R books series











Contact us if you wish to help support R-bloggers, and place your banner here.

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)