The magic empty bracket

January 30, 2013
By

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

I have been working with R for some time now, but once in a while, basic functions catch my eye that I was not aware of…
For some project I wanted to transform a correlation matrix into a covariance matrix. Now, since `cor2cov` does not exist, I thought about “reversing” the `cov2cor` function (`stats:::cov2cor`).
Inside the code of this function, a specific line jumped into my retina:

```r[] <- Is * V * rep(Is, each = p)
```

What’s this [ ]?

Well, it stands for every element $E_{ij}$ of matrix $E$. Consider this:

```mat <- matrix(NA, nrow = 5, ncol = 5)
```
```> mat
[,1] [,2] [,3] [,4] [,5]
[1,]   NA   NA   NA   NA   NA
[2,]   NA   NA   NA   NA   NA
[3,]   NA   NA   NA   NA   NA
[4,]   NA   NA   NA   NA   NA
[5,]   NA   NA   NA   NA   NA```

With the empty bracket, we can now substitute ALL values by a new value:

```mat[] <- 1
```
```> mat
[,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    1    1    1    1    1
[3,]    1    1    1    1    1
[4,]    1    1    1    1    1
[5,]    1    1    1    1    1```

Interestingly, this also works with lists:

```L <- list(a = 1, b = 2, c = 3)

>L
\$a
[1] 1
\$b
[1] 2
\$c
[1] 3
L[] <- 5

> L
\$a
[1] 5

\$b
[1] 5

\$c
[1] 5

Cheers,
Andrej

Filed under: R Internals Tagged: all elements, empty bracket, matrix

var vglnk = { key: '949efb41171ac6ec1bf7f206d57e90b8' };

(function(d, t) {
var s = d.createElement(t); s.type = 'text/javascript'; s.async = true;
var r = d.getElementsByTagName(t)[0]; r.parentNode.insertBefore(s, r);
}(document, 'script'));

Related
ShareTweet

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.