Search code examples
rgamma-distribution

Transform variable to gamma distribution in R


I have a variable that I want to transform to a gamma distribution with known shape and rate parameters. How can I transform the variable to a gamma distribution in R? I've looked into the dgamma, pgamma, and qgamma functions, but I can't tell if any will do what I want.

Here's a small example:

variable <- rnorm(100)
shape <- .83
rate <- .01

Note: I realize this example uses normally distributed data (which doesn't fit a gamma distribution), but I need to rescale the variable to the original gamma distribution.


Solution

  • Use the distribution and quantile functions to translate:

    qgamma(pnorm(variable), shape=.83, rate=.01)
    

    This assumes that variable has mean 0, sd 1 (as it does for your example). Otherwise you can pass the mean and sd into pnorm.

    To see the transformation:

    plot(density(variable))
    

    enter image description here

    plot(density(qgamma(pnorm(variable), shape=.83, rate=.01)))
    

    enter image description here