[R] Raising a vector to the power of elements of another vector

arun smartpink111 at yahoo.com
Wed May 14 04:21:08 CEST 2014


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 




More information about the R-help mailing list