[R] matrix dimension and for loop
ggrothendieck at yifan.net
Wed Apr 10 15:55:26 CEST 2002
> 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'
> 2. and if I don't know the dimension of x, which could
> be only 1 column, how could I write the command
I thought I would collect together some of the solutions that have
been posted as well as mention a few others. I have also added
some discussion particularly with reference to the second question.
There appears to be a myriad of ways to address this problem in R.
Since I am learning R I found it useful for myself to explore various
solutions and maybe others will find this helpful too.
The problem is to multiply the jth column of a matrix x by y[j] for each j.
Its also possible for x to be a vector in which case y may be a scalar.
The first 4 solutions regard x as a one column matrix if x is a vector and
so always return a matrix. The 5th solution returns a vector if x is a
1. Matrix multiplication. Note that if x is a vector then it is treated as a
one column matrix. Also note that NROW(x) is the same as nrow(x), if x is a
matrix; however, if x is a vector, then NROW(x) is its length while nrow(x)
is NULL. Thus it is important here to use NROW and not nrow. This is
discussed in the help on nrow.
x %*% diag(y,NROW(x))
2. Scalar multiplication and transpose. Note that if x is a vector then t(x)
is a row matrix made out of it, so no special processing is necessary.
3. Sweep. Note that as.matrix(x) is the same as x, if x is a matrix, but is a
column matrix made out of x, if x is a vector.
4. Scalar multiplication and col. col(m) is a matrix the same size as
matrix m. Every entry in column j equals j (for all columns).
as.matrix(x) * y[col(as.matrix(x))]
5. Variant of #4. The following is the same as #4 except that it returns a
vector if x is a vector.
x * y[col(as.matrix(x))]
as.matrix(x) can be abbreviated to just x, in #3, #4 and #5
if x is known always to be a matrix. For example, the last two solutions
would be just x*y[col(x)].
I had not expected the last 2 solutions to work in the case that x is a vector
and y is a scalar, since they involve subscripting of a scalar, but apparently
that works in R.
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