Search code examples
rpow

Can I raise a number to the power of a vector in R?


I have a vector and want to raise a number to the power of the vector's elements without using a loop. Is there an easy way to do that?

I tried a^b where a is a number and b is a vector but that doesn't seem to work for me.


Solution

  • The exponentiation operation must be carefully performed in R, since a negative base can give wrong results.

    Wrong

    power <- function(x, y) x^y
    
    power(2, 3)
    #[1] 8
    power(2, -3)
    #[1] 0.125
    
    power(1, 1/3)
    #[1] 1
    power(-1, 1/3)
    #[1] NaN
    

    Right

    power <- function(x, y) sign(x) * abs(x)^y
    
    power(2, 3)
    #[1] 8
    power(2, -3)
    #[1] 0.125
    power(1, 1/3)
    #[1] 1
    power(-1, 1/3)
    #[1] -1
    

    Now see if this second power function is vectorized, like the question asks for.

    power(2, c(1:4, pi, -pi, -1/3, 1/3))
    #[1]  2.0000000  4.0000000  8.0000000 16.0000000  8.8249778  0.1133147
    #[7]  0.7937005  1.2599210
    
    outer(c(-2, 2), c(1:4, pi, -pi, -1/3, 1/3), power)
    #     [,1] [,2] [,3] [,4]      [,5]       [,6]       [,7]      [,8]
    #[1,]   -2   -4   -8  -16 -8.824978 -0.1133147 -0.7937005 -1.259921
    #[2,]    2    4    8   16  8.824978  0.1133147  0.7937005  1.259921