On Dec 12, 2009, at 9:31 AM, Rodrigo Tsai wrote:
> Dear R developers,
>
> is that right?
>
>> -27^(1/3)
> [1] -3
library(fortunes)
> fortune("^")
Thomas Lumley: The precedence of ^ is higher than that of unary minus.
It may be surprising, [...]
Herv? Pag?s: No, it's not surprising. At least to me... In the country
where I grew up, I've been teached that -x^2 means -(x^2) not (-x)^2.
-- Thomas Lumley and Herv? Pag?s (both explaining that operator
precedence is working perfectly well)
R-devel (January 2006)
Also see R FAQ 7.33:
http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-are-powers-of-negative-numbers-wrong_003f
Using the example in the FAQ:
> as.list(quote(-27^(1/3)))
[[1]]
`-`
[[2]]
27^(1/3)
So what you see above is the consequence of operator precedence, thus:
> (-27)^(1/3)
[1] NaN
which is what you are getting below for the first value in the vector.
>> c(-27,27)^(1/3)
> [1] NaN 3
>
> i'm using sign( c(-27,27) ) * abs( c(-27,27)) ^(1/3) ,
> thanks
>
That seems to be a reasonable approach and if memory serves, has been
posted to the list previously.
HTH,
Marc Schwartz