[This article was first published on R Enthusiast and R/C++ hero, 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.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Usually in strongly typed languages, like C++, the type of a variable comes before the variable, e.g.:
int x = 23 ;
So x
is declared of type int
and assignd the value 23
.
Now, some languages do things differently, e.g. in julia:
x::Int8 = 1000
or go :
var i int = 1 ;
So here is a curious thing we can do with R:
`:<-` <- function(x, y, value){ cl <- deparse(substitute(y)) target <- deparse(substitute(x)) if( !is(value, cl) ) { beepr::beep(7) stop(sprintf("incompatible, expecting %s", cl ) ) } assign( target, value, parent.frame() ) }
The idea is that we can do something like this:
x :integer <- 3L x :integer <- "foo"
It does not work if x
does not already exist, which makes this kind of useless:
> x :integer <- 3 Erreur dans x:integer <- 3 : objet 'x' introuvable
However, if x
already exist, it does:
> x <- NULL > x :integer <- 3L > x [1] 3 > x :integer <- "foo" Erreur dans `:<-`(`*tmp*`, integer, value = "foo") : incompatible, expecting integer
This is not particularly useful. For it to be more useful, we would need the R grammar to recognize a:b <- c
and do something meaningful with it.
To leave a comment for the author, please follow the link and comment on their blog: R Enthusiast and R/C++ hero.
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.