[R] a^c(1:3)

David Winsemius dwinsemius at comcast.net
Tue Sep 7 18:51:42 CEST 2010


On Sep 7, 2010, at 12:35 PM, Feng Li wrote:

> Dear R,
>
> I have two small questions confused me recently. Now assume I have a  
> matrix
> "a", like this,
>
>> a <- matrix(1:6, 2, 3)
>> a
>     [,1] [,2] [,3]
> [1,]    1    3    5
> [2,]    2    4    6
>
> I sometimes need each row of "a" raised to a different exponent. So  
> I do a
> trick like this,
>
>> a^c(2, 3)
>     [,1] [,2] [,3]
> [1,]    1    9   25
> [2,]    8   64  216
>
> My first question is that if it is possible to do this trick column  
> wise?

Most questions of this sort are answerable by thinking of R matrices  
as folded vectors. The folding occurs columnwise (unlike Matlab), so  
for this problem:

> > a^rep(c(2, 3, 4), each=nrow(a)) #  the exponents become 2,2,3,3,4,4
>      [,1] [,2] [,3]
> [1,]    1   27  625
> [2,]    4   64 1296
>

or:

 > a^matrix(c(2, 3, 4), byrow=TRUE, nrow=2, ncol=3)
      [,1] [,2] [,3]
[1,]    1   27  625
[2,]    4   64 1296

> Just out of curiosity, of course I know there are other ways of  
> doing this.
>
> And the second question is why I get such result when I put another  
> element
> in the exponent part like this,

Because argument recycling makes the exponents 2,3,4,2,3,4 and they  
are applied folded column wise
>
>> a^c(2, 3, 4)
>     [,1] [,2] [,3]
> [1,]    1   81  125
> [2,]    8   16 1296
>
>
>
> BTW, I have a 64bit R version (2.11) for Linux. Any advice would be
> appreciated.


David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list