Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Warn users about nonstandard evaluation #4

Open
nhejazi opened this issue Sep 28, 2017 · 2 comments
Open

Warn users about nonstandard evaluation #4

nhejazi opened this issue Sep 28, 2017 · 2 comments

Comments

@nhejazi
Copy link
Member

nhejazi commented Sep 28, 2017

Apparently, delayed appears to interact in an odd way with repeated calls to functions that generate random variates. In particular, the expression replicate(3, rnorm(100)) will produce a matrix with 3 columns, each corresponding to 100 random draws from a N(0, 1) distribution. This is not the case when one invokes delayed(replicate(3, rnorm(100)))$compute(), which returns a matrix of similar form but with each of the 3 columns being exactly the same.

@jeremyrcoyle
Copy link
Collaborator

jeremyrcoyle commented Sep 28, 2017

This is actually an issue with the interaction between delayed and replicate. Both delayed and replicate use nonstandard evaluation (NSE), and their usage conflicts.

delayed evaluates all function arguments before calling a function to determine if they themselves are delayed, and then passes the results of those evaluations to the function call. Here, that means evaluating rnorm(100) and calling replicate on its result. In contrast, replicate captures the expression passed to its second argument unevaluated, and then repeatedly evaluates it.

You could generate something equivalent to replicate(3, rnorm(100)) with delayed(sapply(1:3,function(x)rnorm(10)))$compute(), because sapply doesn't use NSE.

It seems worth warning the user to be careful with the combination of delayed and other functions that use NSE. Do you think the vignette is a good place for this? There's a good discussion on related issues here: http://adv-r.had.co.nz/Computing-on-the-language.html#nse-downsides

@nhejazi
Copy link
Member Author

nhejazi commented Sep 28, 2017

Ok, good to know. Yes, I think it's worth adding an "Advanced" section to the vignette that warns users about these sorts of situations, perhaps with a reference to Hadley's book.

@jeremyrcoyle jeremyrcoyle changed the title Delaying random number generation Warn users about nonstandard evaluation Sep 28, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants