[R] How to remove double for loop?

Bill.Venables at csiro.au Bill.Venables at csiro.au
Wed Mar 19 13:37:19 CET 2008


One possibility might be

Val <- outer(0:n, 0:n, function(i, j) ifelse(i <= j, u^i*d^(j-i), 0)) 

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org]
On Behalf Of Jonas Malmros
Sent: Wednesday, 19 March 2008 9:24 PM
To: r-help at r-project.org
Subject: [R] How to remove double for loop?

Hello everyone.

I use double for loops to fill in matrices, but there are surely
better (and computationally faster) ways to perform that task.
Could someone show me, given the following example of a double for
loop, how this could be done? It is much easier to learn by examples.

Val <- matrix(0, nrow=n+1, ncol=n+1)
for( i in 0:n){
    for(j in 0:i){
        Val[j+1, i+1] <- u^j*d^(i-j)
    }
}

Thank you in advance!

-- 
Jonas Malmros

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list