Skip to content

Instantly share code, notes, and snippets.

@thomas-neitmann
Last active September 11, 2020 15:44
Show Gist options
  • Save thomas-neitmann/e25b23fcc6d56a3fc4c449305282c9f6 to your computer and use it in GitHub Desktop.
Save thomas-neitmann/e25b23fcc6d56a3fc4c449305282c9f6 to your computer and use it in GitHub Desktop.
`:=` <- function(lhs, rhs) {
var <- deparse(substitute(lhs))
if (exists(var, parent.frame(), inherits = FALSE)) {
stop("Variable `", var, "` is already defined.", call. = FALSE)
} else {
assign(var, rhs, parent.frame())
}
}
# An alternative version making use of `lockBinding`. This prevents users from overwriting
# the variable using `<-`, `->` or `=` later on. The former variant would only throw an error
# when using `:=` again.
`:=` <- function(var, value) {
id <- deparse(substitute(var))
assign(id, value, parent.frame())
lockBinding(id, parent.frame())
invisible(value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment