a:class <- b

July 28, 2014

(This article was first published on R Enthusiast and R/C++ hero, and kindly contributed to R-bloggers)

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

Comments are closed.

Search R-bloggers


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)