[R] Avoiding a Loop?
Berton Gunter
gunter.berton at gene.com
Fri Jan 21 18:47:01 CET 2005
Roland:
Andy Liaw and others have already given perfectly good answers to this (but
note: Using apply() type functions does **not** avoid loops; apply's **are**
loops). However, mostly as an illustration to reinforce Uwe Ligges's
comments (in the "dim vs length" thread) about the usefulness of sometimes
treating arrays as vectors, I offer the following:
nc<-ncol(yourmatrix)
matrix(yourmatrix[,1]*rep(k^seq(0,length=nc),e=nrow(yourmatrix)),ncol=nc)
Alteratively, one could use matrix multiplication:
yourmatrix[,1]%*%matrix(k^seq(0,length=nc),nrow=1)
Both of these will be very fast (although unlikely to make a noticeable
difference without a lot of rows or columns) and I think use less memory
than outer() (again, unlikely to make a noticeable difference).
-- Bert Gunter
Genentech Non-Clinical Statistics
South San Francisco, CA
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Rau, Roland
> Sent: Friday, January 21, 2005 4:32 AM
> To: r-help at stat.math.ethz.ch
> Subject: [R] Avoiding a Loop?
>
> Dear R-Helpers,
>
> I have a matrix where the first column is known. The second column is
> the result of multiplying this first column with a constant
> "const". The
> third column is the result of multiplying the second column with
> "const".....
> So far, I did it like this (as a simplified example):
>
> nr.of.columns <- 4
>
> myconstant <- 27.5
>
> mymatrix <- matrix(numeric(0), nrow=5, ncol=nr.of.columns)
>
> mymatrix[,1] <- 1:5
>
> for (i in 2:nr.of.columns) {
> mymatrix[,i] <- myconstant * mymatrix[,i-1]
> }
>
>
> Can anyone give me some advice whether it is possible to
> avoid this loop
> (and if yes: how)?
>
> Any suggestions are welcome!
>
> Thanks,
> Roland
>
>
>
>
> +++++
> This mail has been sent through the MPI for Demographic
> Rese...{{dropped}}
>
> ______________________________________________
> R-help at 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
>
More information about the R-help
mailing list