Hi,
I think this is substantially less ugly:
A <- matrix(1:15,nrow=5,byrow=F); A
a <- c(1,2,3)
B <- sweep(A, 2, a, "^")
apply(B, 1, prod)
You could combine it into one line if you wanted, but I find it clearer as two:
> apply(sweep(A, 2, a, "^"), 1, prod)
[1] 47916 169344 421824 889056 1687500
Sarah
On Fri, Jul 1, 2016 at 10:15 AM, Steven Yen <syen04 at gmail.com>
wrote:> A is a 5 x 3 matrix and a is a 3-vector. I like to exponentiate A[,1] to
> a[1], A[,2] to a[2], and A[,3] to a[3], and obtain the product of the
> resulting columns, as in line 3.
>
> I also accomplish this with lines 4 and 5. I like to have rowProducts(B)
> but there is not so I came up with something ugly in line
> 5--exponentiating the row sums of log. Is there a more elegant way than
> than line 5 or, better yet, lines 4 and 5 together? Thanks.
>
> A<-matrix(1:15,nrow=5,byrow=F); A
> a<-c(1,2,3)
> (A[,1]^a[1])*(A[,2]^a[2])*(A[,3]^a[3])
> B<-t(t(A)^a); B
> exp(rowSums(log(B)))
>
> Result:
>
> > A<-matrix(1:15,nrow=5,byrow=F); A
> [,1] [,2] [,3]
> [1,] 1 6 11
> [2,] 2 7 12
> [3,] 3 8 13
> [4,] 4 9 14
> [5,] 5 10 15
> > a<-c(1,2,3)
> > (A[,1]^a[1])*(A[,2]^a[2])*(A[,3]^a[3])
> [1] 47916 169344 421824 889056 1687500
> > B<-t(t(A)^a); B
> [,1] [,2] [,3]
> [1,] 1 36 1331
> [2,] 2 49 1728
> [3,] 3 64 2197
> [4,] 4 81 2744
> [5,] 5 100 3375
> > exp(rowSums(log(B)))
> [1] 47916 169344 421824 889056 1687500
> >