[R] Avoiding for loop

From: Matt Crawford <mcrawford_at_gmail.com>
Date: Fri 05 Aug 2005 - 09:25:40 EST

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:


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.

R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Fri Aug 05 09:29:37 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:39:42 EST