[R] Avoiding a Loop?

Rau, Roland Rau at demogr.mpg.de
Fri Jan 21 16:07:26 CET 2005


Dear R-List,

thank you very much for the fast answers.
Andy Liaw and James Holtman both gave me some example code which does
exactly what I want.

I will now try to check which one is better suited for my actual matrix
(in terms of speed).

Thanks,
Roland


-----Original Message-----
From: james.holtman at convergys.com [mailto:james.holtman at convergys.com] 
Sent: Friday, January 21, 2005 3:57 PM
To: Rau, Roland
Cc: r-help at stat.math.ethz.ch; r-help-bounces at stat.math.ethz.ch
Subject: Re: [R] Avoiding a Loop?





Does this do what you want?

nr.of.columns <- 4

myconstant <- 27.5

mymatrix <- matrix(myconstant, nrow=5, ncol=nr.of.columns)

mymatrix[,1] <- 1:5

t(apply(mymatrix, 1, function(x) cumprod(x)))


__________________________________________________________
James Holtman        "What is the problem you are trying to solve?"
Executive Technical Consultant  --  Office of Technology, Convergys
james.holtman at convergys.com
+1 (513) 723-2929


 

                      "Rau, Roland"

                      <Rau at demogr.mpg.de>          To:
<r-help at stat.math.ethz.ch>

                      Sent by:                     cc:

                      r-help-bounces at stat.m        Subject:  [R]
Avoiding a Loop?

                      ath.ethz.ch

 

 

                      01/21/2005 07:31

 

 





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





+++++
This mail has been sent through the MPI for Demographic Rese...{{dropped}}




More information about the R-help mailing list