[R] a^c(1:3)

Erik Iverson eriki at ccbr.umn.edu
Tue Sep 7 18:45:25 CEST 2010


Feng,

Hello, all of this behavior comes down to argument recycling.

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

Right, so you have

as.vector(a)
[1] 1 2 3 4 5 6

and

a^c(2,3)

will then use argument recycling to compute

1^2 2^3 3^2 4^3 5^2 6^3

and then return the matrix in its original dimension.

> 
> My first question is that if it is possible to do this trick column wise?

Yes, just use t to transpose.

> 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,
> 
>> a^c(2, 3, 4)
>      [,1] [,2] [,3]
> [1,]    1   81  125
> [2,]    8   16 1296

Same reason as it worked above, argument recycling, now you get

1^2 2^3 3^4 4^2 5^3 6^4

> 
> 
> 
> BTW, I have a 64bit R version (2.11) for Linux. Any advice would be
> appreciated.
> 
> 
> 
> Feng
>



More information about the R-help mailing list