rgamma-distributiongamma-function

Inverse of gamma function with R


With gamma() in R you get output 24 from input 5. How can I make inverse function which can get output 5 from input 24?

>gamma(5)
24

I found [invgamma] package, but I can’t understand if it is appropriate one nor how to use it…


Solution

  • Use uniroot to find the root of gamma(x) - a, where a is your number.

    invgamma <- function(a, tol = .Machine$double.eps^0.5) {
      uniroot(\(x) gamma(x) - a, c(1, 1e2), extendInt = "upX", tol = tol)
    }
    
    invgamma(24)$root
    #> [1] 5
    
    invgamma(24)
    #> $root
    #> [1] 5
    #> 
    #> $f.root
    #> [1] -5.207212e-11
    #> 
    #> $iter
    #> [1] 19
    #> 
    #> $init.it
    #> [1] NA
    #> 
    #> $estim.prec
    #> [1] 7.450582e-09
    

    Created on 2024-09-29 with reprex v2.1.0

    You can vectorize this function.

    igamma <- Vectorize(invgamma, "a")
    igamma(c(6, 24, 120)) |> t()
    #>      root f.root        iter init.it estim.prec  
    #> [1,] 4    -2.771117e-13 17   NA      7.450582e-09
    #> [2,] 5    -5.207212e-11 19   NA      7.450582e-09
    #> [3,] 6    2.727063e-11  18   NA      7.450583e-09
    

    Created on 2024-09-29 with reprex v2.1.0