[R] matrix dimension and for loop

Douglas Bates bates at stat.wisc.edu
Tue Apr 9 16:54:56 CEST 2002


sonchawan tamkaew <psu17772 at yahoo.com> writes:

> 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?

Yes.  If you multiply (i.e. the '*' operator) a matrix and a vector
you will do operations columnwise on the matrix.  Here you want to
multiply the rows so you could transpose x, multiply by y and
transpose the result.

> x <- array(rnorm(50), dim = c(10,5))
> dim(x)
[1] 10  5
> y <- 1:5
> Z <- t(y * t(x))
> dim(Z)
[1] 10  5
> x[1,]
[1]  0.23144399 -0.25393369  0.06469486 -0.13116405  0.48534804
> Z[1,]
[1]  0.2314440 -0.5078674  0.1940846 -0.5246562  2.4267402

> 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.

The above will work in that case too.

> x <- rnorm(10)
> y <- 2
> t(y * t(x))
            [,1]
 [1,]  1.5755705
 [2,]  0.3811325
 [3,] -0.4629773
 [4,]  1.7612785
 [5,]  0.7881174
 [6,] -0.2815202
 [7,]  0.4315893
 [8,]  1.1609736
 [9,]  1.8737894
[10,]  5.3069982
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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