4

I am trying to use the nthroot function from the pracma package. However, whenever I run it I get an error:

Error in nthroot(x, 5) : could not find function "nthroot"

I tried installing the pracma package but that didn't help either. Could anyone give me any ideas on why this isn't working?

Cettt
  • 11,460
  • 7
  • 35
  • 58
kronokrusader
  • 43
  • 4
  • 5
  • have you loaded the library before using the `nthroot` function. First execute `library(nthroot)`. Alternatively you can try `pracma::nthroot(x, 5)`, – Cettt Oct 18 '19 at 08:58
  • 4
    Sorry if I am missing something obvious, but it sounds like an arbitrary enough function to declare yourself. `nthroot = function(x, n){x^(1/n)}`, `> nthroot(4, 2) [1] 2` – JDG Oct 18 '19 at 08:58
  • @J.G. Yes, it's easy, but be careful with the sign: nthroot(-8,3) should be -2 , not NaN. – Hans W. Oct 18 '19 at 19:02

2 Answers2

5

nthroot handles negatives, e.g. returning nthroot(-2,3) == -1.259921, rather than NA

To define this yourself:

nthroot = function(x,n) {
  (abs(x)^(1/n))*sign(x)
}
  • Nothing wrong with returning -1.26, that's just the real‐valued root. If you're aiming for the *principal* root, the decimal approximation would be around 0.63 + 1.09. No need for `NA` there, `x ^ (1 / n)` is just fine since the real‐valued root is okay here I think. – MS Berends Oct 15 '21 at 07:12
  • 1
    Yes, the function I've defined returns -1.26. I think in some older versions of R, `x^(1/n)` used to return NA or NaN for negative x (see Hans W's comment on the original post) - but I've just checked in v4.0.4 and your solution gives exactly the same answer as mine. So, either solution works nicely :-) – ChrisWResearch Dec 03 '21 at 10:21
4

Just do

x ^ (1 / n)

Where n is the root.

MS Berends
  • 4,489
  • 1
  • 40
  • 53