Hi,
May be this helps:

a <- 1:3
 b <- 2:4
Mnew <- matrix(a^(rep(b, each=length(a))),ncol=3,byrow=TRUE)
identical(M,Mnew)
#[1] TRUE
#or
 M1 <-t(outer(a,b, FUN="^"))
identical(M,M1)
#[1] TRUE
#or
dat <- expand.grid(a,b)
M2 <- matrix(dat[,1]^dat[,2],ncol=3,byrow=TRUE)
identical(M,M2)
#[1] TRUE


A.K.

Hi all,

Suppose I have a vector a<-c(1,2,3) and I want to raise it to the power of 2, 
3, 4 and bind it into a matrix that looks like 
M<-matrix(c(1,1,1,4,8,16,9,27,81),3,3). Let the vector with elements 2,3,4 be 
called b. Can I manipulate a and b to get M without using loops? I have a 
massive data and if I use loops it takes very long time.
So far I have just tried using loops:
Loopy<-lapply(1:3,function(s){
           a^b[s]
})
Loopyfinal<-do.call(rbind,Loopy)
I would appreciate a nicer trick, if there is one.
Thanks,
Delger 


______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to