[R] matrix dimension and for loop
Jonathan Baron
baron at cattell.psych.upenn.edu
Tue Apr 9 16:42:01 CEST 2002
On 04/09/02 05:46, sonchawan tamkaew wrote:
>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?
x <- matrix(rnorm(50),10,5) # collapsing your first two commands
y <- 1:5
Z <- matrix(0,nrow(x),length(y)) # case sensitive, and y is a vector
Z[,length(y)] <- x %*% y
It isn't clear that this is what you want, though. It fills up
one column of Z.
>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.
I think it will still work. So long as you pay attention to what
is a matrix - to which dim() applies - and what is a vector, to
which length() applies.
--
Jonathan Baron, Professor of Psychology, University of Pennsylvania
Home page: http://www.sas.upenn.edu/~baron
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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