[R] trivial question about nested loops

dan roberts bro092 at yahoo.com
Thu Sep 2 18:52:07 CEST 2004


Duncan,

I tried your solutions and they almost work. The problem seems
to be d$Y[k]. When I run the code with d$Y[k], I get an empty
matrix (all 0s). However, if I replace d$Y[k] with, for example,
d&Y4, then I get a matrix with one of the results I am looking
for. Do you have any idea how I could make d$Y[k] actually pull
the columns from the imported table (d$Y1, d$Y2, ...)?
I tried
sum(paste("d$Y",k,sep="")*exp(-1i*j*d$X)) 
but I got 
Error in paste("d$Y", k, sep = "") * exp(-(0+1i) * j * d$X) : 
        non-numeric argument to binary operator

Thanks,
dan

d <- read.delim('ft.txt', header = TRUE, sep = "\t", quote="\"",
dec=".", fill = TRUE)
n <- 5
f <- matrix(vector(mode="complex",n^2),n,n)
for (k in 1:n) {
	for(j in 1:n) 
		f[k,j] <- sum(d$Y[k]*exp(-1i*j*d$X)) 
}





--- Duncan Murdoch <murdoch at stats.uwo.ca> wrote:

> 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