Hermi
Hermi

Reputation: 357

How to get the quantile of a data_frame?

I wrote a function

 rnormgamma <- function(n, mu, lambda, alpha, beta) {
   if (length(n) > 1) 
     n <- length(n)
  tau <- rgamma(n, alpha, beta)
  x <- rnorm(n, mu, sqrt(1/(lambda*tau)))
   data.frame(tau = tau, x = x)
  }

I got data.frame taubeta of x and tau if I sample

  taubeta <- rnormgamma(10000, 0.3, 70000, 11, 600)

If I want to get the quantile of x and tau, respectively. How to write this code in R?

Upvotes: 0

Views: 88

Answers (3)

Vincent
Vincent

Reputation: 17715

Here is a solution that only requires "base" R packages (no need for libraries.

Use sapply to apply a function to each column of a data.frame and quantile to calculate the actual quantiles:

sapply(taubeta, quantile)
#>              tau         x
#> 0%   0.004361796 0.1711136
#> 25%  0.014334854 0.2816301
#> 50%  0.017776155 0.3005732
#> 75%  0.021656277 0.3192821
#> 100% 0.051708122 0.4302409

You can specify which quantiles you want with the probs argument:

sapply(taubeta, quantile, probs=c(.5, .8))
#>            tau         x
#> 50% 0.01777528 0.2996857
#> 80% 0.02275949 0.3238543

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388982

You can use sapply/lapply to get quantile values for each column.

sapply(taubeta, quantile)

#             tau         x
#0%   0.004187748 0.1376232
#25%  0.014378060 0.2805112
#50%  0.017700113 0.2994879
#75%  0.021724271 0.3187546
#100% 0.048315654 0.4180485

Upvotes: 1

Abdessabour Mtk
Abdessabour Mtk

Reputation: 3888

Using dplyr's summarise and across functions this can be achieved with the following code:

library(dplyr)

taubeta %>% summarise(across(everything(),quantile, probs=c(.025, .975) ))

## or with the summarise_all function
taubeta %>% summarise_all(quantile, probs=c(.025,.975) )

Output

          tau         x
1 0.009166053 0.2420291
2 0.030686640 0.3580429

Upvotes: 1

Related Questions