问题描述
rnormgamma <- function(n,mu,lambda,alpha,beta) {
if (length(n) > 1)
n <- length(n)
tau <- rgamma(n,beta)
x <- rnorm(n,sqrt(1/(lambda*tau)))
data.frame(tau = tau,x = x)
}
我获得了taubeta
和x
的data.frame tau
taubeta <- rnormgamma(10000,0.3,70000,11,600)
如果我想分别获得x
和tau
的分位数。如何在R中编写此代码?
解决方法
使用dplyr
的{{1}}和summarise
函数可以通过以下代码实现:
across
输出
library(dplyr)
taubeta %>% summarise(across(everything(),quantile,probs=c(.025,.975) ))
## or with the summarise_all function
taubeta %>% summarise_all(quantile,.975) )
,
您可以使用sapply
/ lapply
来获取每一列的quantile
值。
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
,
这是一个仅需要“基本” R程序包(不需要库的解决方案)。
使用sapply
将一个函数应用于data.frame的每一列,并使用quantile
计算实际的分位数:
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
您可以使用probs
参数指定所需的分位数:
sapply(taubeta,probs=c(.5,.8))
#> tau x
#> 50% 0.01777528 0.2996857
#> 80% 0.02275949 0.3238543