R vs. Matlab – a small example

[This article was first published on "R" you ready?, 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.

At the institute I’m working quite a lot of people prefer using Matlab and only a few of them know about R. Today one of my colleagues — who is also an eager user of Matlab — ran into the following problem:

  • He had a vector v in hand which consisted of \frac{n(n+1)}{2} elements.
  • He wanted to reshape this data into an n×n matrix M, where the element M_{ij} is equal to v_{k+j}I(j<=n-i+1) with k=\frac{(2n-i+2)(i-1)}{2} and I(j <= n-i+1)=1 if the condition j <= n-i+1 is satisfied and 0 otherwise. In other words, the first (n-i+1)th element of the ith row of M is equal to the vector (v_{k+1},v_{k+2},\ldots,v_{k+n-i+1}) and the remaining elements are zero.

He struggled for long minutes of how he should design a loop for doing this task. Of course writing such a loop is not a highly difficult task, but why would we waste our time, if we can get the same result in a single line of R code?

For the sake of illustration, I’ve generated an input vector for the case of n=99 (the value of n was 99 in my colleague’s problem as well):

v <- rep(99:1,times=99:1)

and used the one-liner

M <- t(matrix(unlist(tapply(v,rep(1:99,times=99:1),function(x) c(x,rep(0,99-length(x))))),nrow=99))

This is the kind of compactness I like pretty much in R. At the end I would like to emphasize that this post is not against Matlab, it just points out how the different logic of the R language can simplify problem solving in many situations. As a bonus let me share the visualization of the resulted matrix using the color2D.matplot function of the plotrix package:
library(plotrix) color2D.matplot(M,c(0,1),c(1,0),c(0,0))


To leave a comment for the author, please follow the link and comment on their blog: "R" you ready?.

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.

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)