[R] Avoiding for loop

Matt Crawford mcrawford at gmail.com
Fri Aug 5 01:25:40 CEST 2005


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.




More information about the R-help mailing list