[R] R: to the power

Robin Hankin r.hankin at noc.soton.ac.uk
Tue Jul 12 15:29:48 CEST 2005


Hi

I find that one often needs to keep reals real and complexes complex.

Try this:

"cuberooti" <-
   function (x)
{
   if (is.complex(x)) {
     return(sqrt(x + (0+0i)))
   }
   sign(x)*  abs(x)^(1/3)
}


best wishes

[see that (0+0i) sitting there!]

Robin



On 12 Jul 2005, at 14:11, allan_sta_staff_sci_main_uct at mail.uct.ac.za  
wrote:

> hi all
>
> why does R do this:
>
> (-8)^(1/3)=NaN
>
> the answer should be : -2
>
> a silly question but i kept on getting errors in some of my code  
> due to this
> problem.
>
> i solve the problem as follows:
>
> say we want : (-a)^(1/3)
>
> then : sign(a)*(a^(1/3)) works
>
> but there has to be a simpler way of soing such a simple  
> mathematical operation.
>
> thanking you
> /
> allan
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting- 
> guide.html
>

--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743




More information about the R-help mailing list