[R] Avoiding a Loop?

Liaw, Andy andy_liaw at merck.com
Fri Jan 21 15:32:42 CET 2005


If `v' the the vector in the first column and `k' is the constant, then the
matrix has k^(j-1) * v in the jth column, right?

> k <- 27.5^seq(0, length=4)
> k
[1]     1.00    27.50   756.25 20796.88
> outer(1:5, k, "*")
     [,1]  [,2]    [,3]      [,4]
[1,]    1  27.5  756.25  20796.88
[2,]    2  55.0 1512.50  41593.75
[3,]    3  82.5 2268.75  62390.63
[4,]    4 110.0 3025.00  83187.50
[5,]    5 137.5 3781.25 103984.38

Andy

> From: Rau, Roland
> 
> 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