[R] matrix dimension and for loop

ggrothendieck@yifan.net ggrothendieck at yifan.net
Tue Apr 9 19:23:14 CEST 2002


On 9 Apr 2002 at 5:46, sonchawan tamkaew wrote:

> Dear all,
> 
> My questions are that if I have
> 
> > x<-rnorm(50)
> > dim(x)<-c(10,5)
> > y=1:5
> > Z<-matrix(0,NROW(x),NROW(y))
> > for (j in 1:NROW(y)) Z[,j]<-x[,j]*y[j]
> 
> 1. Is there any other way to write this without 'for'
> loop?

Z <- t( t(x) * y )

> 
> 2. and if I don't know the dimension of x, which could
> be only 1 column, how could I write the command
> without using if (NCOL(x)==1), or something like that?
> (in case I want to include them in my function.
> 
> Example of x is a vector.
> > x<-rnorm(10)
> > y=2
> > Z<-matrix(0,NROW(x),NROW(y))
> > for (j in 1:NROW(y)) Z[,j]<-x[,j]*y[j]
> Error in x[, j] : incorrect number of dimensions

The answer already given to theprevious
question automatically handles the case 
where x is a vector so its not necessary to 
provide special code for it.

However, even though its not needed here,
just for interest:

x <- as.matrix( x ) 

will turn vector x into a 1 column matrix and leave it
as is if its already a matrix.


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list