[R] trivial question about nested loops
Duncan Murdoch
murdoch at stats.uwo.ca
Thu Sep 2 16:50:19 CEST 2004
On Thu, 2 Sep 2004 07:26:31 -0700 (PDT), dan roberts
<bro092 at yahoo.com> wrote :
>Hello,
>
>It's a trivial question but I haven't found a solution in the
>full reference manual. How can I make the code below run?
Probably most easily if f was a list of lists (see solution 1 below).
>Would
>an array/matrix solution be faster? Please provide a short
>example, if possible.
Yes if the problem were bigger; see solution 2 below. With the 5x5
size, you won't notice any difference.
>
>Thanks in advance,
>dan
>
>for (k in 1:5)
> assign(paste("f",k,sep=""),vector(mode="complex",5))
>for (k in 1:5) {
> for(j in 1:5)
> f[k][[j]] <- sum(d$Y[k]*exp(-1i*j*d$X)) }
>Error: Object "f" not found
>
>(I want f[k] to become f1,...,f5; and d$Y[k] should be
>d$Y1,...,d$Y5.)
>
Solution 1:
f <- list()
for (k in 1:5) {
f[[k]] <- list()
for(j in 1:5)
f[[k]][[j]] <- sum(d$Y[k]*exp(-1i*j*d$X))
}
for (k in 1:5)
assign(paste("f",k,sep=""),f[[k]])
Solution 2:
f <- matrix( vector(mode="complex", 25), 5, 5)
for (k in 1:5) {
for(j in 1:5)
f[k,j] <- sum(d$Y[k]*exp(-1i*j*d$X))
}
for (k in 1:5)
assign(paste("f",k,sep=""),f[k,])
More information about the R-help
mailing list