Skip to content

Instantly share code, notes, and snippets.

@klmr
Last active November 5, 2015 13:53
Show Gist options
  • Save klmr/e585031913e926352258 to your computer and use it in GitHub Desktop.
Save klmr/e585031913e926352258 to your computer and use it in GitHub Desktop.
Properly scoped `for` in R.
`for` = function (var, seq, expr) {
eval(substitute(.Primitive('for')(var, seq, expr),
list(var = substitute(var),
seq = substitute(seq),
expr = substitute(expr))))
}
for (i in 1 : 5) {
j = i
cat(i)
}
# 12345
i
# Error: object 'i' not found
j
# Error: object 'j' not found
@klmr
Copy link
Author

klmr commented Nov 5, 2015

Of course the above is merely a proof of concept and fails when there’s a conflict between variable names in the expressions and the argument names. For instance, this fails:

seq = 10
for (var in 1 : seq) print (var)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment