Re: [R] Avoiding for loop

From: Thomas Lumley <tlumley_at_u.washington.edu>
Date: Fri 05 Aug 2005 - 09:31:17 EST

On Thu, 4 Aug 2005, Matt Crawford 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.)
>

This may be a job for matrix indexes

    ii<-1:nrow(rawdata)
    X[cbind(ii,rawdata[,1])] <- 1
    X[cbind(ii,rawdata[,2])] <- -1

         -thomas



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:36:50 2005

This archive was generated by hypermail 2.1.8 : Sun 23 Oct 2005 - 15:05:15 EST