# Re: [R] Avoiding for loop

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Fri 05 Aug 2005 - 11:35:02 EST

On 8/4/05, Matt Crawford <mcrawford@gmail.com> wrote:
> I understand that in R, for loops are not used as often as other
> languages, and am trying to learn how to avoid them. I am wondering
> if there is a more efficient way to write a certain piece of code,
> which right now I can only envision as a for loop. I have a data file
> that basically looks like:
> 1,55
> 1,23
> 2,12
> ...
> that defines a matrix. Each row of the data file corresponds to a row
> of the matrix, where each number in the row tells me what column a "1"
> or "-1" should go into. So the first row in the data snippet above
> means that the first row of my matrix needs to have a 1 in the 1st
> column, and a -1 in the 55nd column. (And 0 elsewhere, which is
> already there as I've created the matrix filled with 0s beforehand.)
>
> So my current code looks like:
> if(nrow(rawdata) >= 1) for(i in 1:nrow(rawdata)) {
> X[i, rawdata[i, 1]] <- 1
> X[i, rawdata[i, 2]] <- -1
> }
>
> where rawdata is the original data file.
> This sort of assignment happens many times in my program so any
> improvement would be much appreciated. Thanks.

idx <- seq(length = max(rawdata, 0))
X <- outer(rawdata[,1], idx, "==") - outer(rawdata[,2], idx, "==")

Note that we did not have to predefine X and it also works if rawdata has zero rows:

rawdata <- matrix(0, nr = 0, nc = 2)

in which case it gives a 0 by 0 matrix.

R-help@stat.math.ethz.ch mailing list