Here you will find daily news and tutorials about R, contributed by over 573 bloggers.
There are many ways to follow us - By e-mail:On Facebook: If you are an R blogger yourself you are invited to add your own R content feed to this site (Non-English R bloggers should add themselves- here)

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 in hand which consisted of elements.

He wanted to reshape this data into an n×n matrix , where the element is equal to with and if the condition is satisfied and otherwise. In other words, the first th element of the th row of is equal to the vector 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 (the value of 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))

Related

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