user44796
user44796

Reputation: 1219

Raising vector with negative numbers to a fractional exponent in R

I have a vector of numbers that contains negative numbers and I would like to raise it to a fractional exponent, but can't quite figure out how to do it. Here is some example code.

a = seq(5,-5,1)
b = a^(5/2)

b returns NAN values when a is negative. However,

d = -5^(5/2) 

works. I know that this is because of precedence in R, but how to do I what I want, which is to multiply by the absolute value of a, and then assign the negative (while also assessing the possibility that a == 0)?

I know this is more of math and R question than statistics, so if it needs to be moved I will do so.

Upvotes: 3

Views: 5096

Answers (3)

Lutz Lehmann
Lutz Lehmann

Reputation: 25992

Your contradictory result stems from the fact that the power as a kind of multiplication binds stronger than the negation. I.e.,

-5^(5/2) = - ( 5^(5/2) ).

This kind of fractional power should rightly not be defined for negative arguments. It would be the solution of

x^2 = (-5)^5 = - 5^5

which is impossible to solve in real numbers.

Fractional powers of complex numbers is a can of worms that you really should not want to open.

Upvotes: 0

Sycorax
Sycorax

Reputation: 1386

exponent <- function(a, pow) (abs(a)^pow)*sign(a)

Upvotes: 11

Richard Hardy
Richard Hardy

Reputation: 407

b = rep(NA,length(a))       # create a vector of length equal to length of a
b[a>=0] =  ( a[a>=0])^(5/2) # deal with the non-negative elements of a
b[a< 0] = -(-a[a< 0])^(5/2) # deal with the negative elements of a

Maybe not the most efficient way to do it, but the idea should be usable.

Upvotes: 2

Related Questions