前段时间我曾询问过为R的采样函数动态分配参数的方法 . 理想情况下,我只想在开头澄清感兴趣的采样分布,然后在参数列表中放入我想要的任何参数(以任何顺序),我在那里得到了一些精彩的答案:
R rnorm Arguments as character
也可以轻松地为pdfs,...等重写此代码 . 1)我现在想将其扩展到多变量分布,但有点卡住并且还没有找到问题的解决方案 . 2)我也想在这个包装器中使用示例函数,但这里也失败了 . 我提供了工作函数的示例代码,以及我没有弄清楚的2个问题 .
############################################################################
# Load Packages
library(tmvtnorm) # to sample from an MV Normal Distribution
############################################################################
#Parameter of Interest
MeanUnivariate <- c(5, -5)
SigmaUnivariate <- c(1, 1)
MeanMultivariate <- c(-10,10)
SigmaMultivariate <- matrix(c(4,2,2,3), ncol=2)
ParameterUnivariate <- list(mean = MeanUnivariate,
sd = SigmaUnivariate
)
ParameterMultivariate <- list(mean = MeanMultivariate,
sigma = SigmaMultivariate,
lower = rep(-Inf, length = length( MeanMultivariate ) ),
upper = rep( Inf, length = length( MeanMultivariate ))
)
############################################################################
#Sampling function
sampling <- function(fun, n, params){
do.call(Vectorize(fun),c(list(n=n),params) )
}
############################################################################
#Working Example
#Univariate
rnorm(2, mean = MeanUnivariate, sd = SigmaUnivariate )
sampling(fun = rnorm,
n = c(1),
params = ParameterUnivariate)
############################################################################
############################################################################
############################################################################
#Not properly working Example 1 - Multivariate Distribution
# It does output something, but "mu" times the amount of RV that are needed for a given n
rtmvnorm(n=2, mean= MeanMultivariate, sigma=SigmaMultivariate,
lower=rep(-Inf, length = length(MeanMultivariate)), upper=rep( Inf, length = length(MeanMultivariate) ) )
sampling(fun = rtmvnorm,
n = c(3),
params = ParameterMultivariate)
#Not properly working Example 2
# This does not give a proper output, as I cannot figure out how x & prob interact in a vectorized environment
#Minimal code adjustment
sampling2 <- function(fun, x, params){
do.call(Vectorize(fun),c(list(x=x),params) )
}
Dice <- 1:6
sample(x = Dice, size = 10 , replace = TRUE, prob = rep(1/length(Dice), length(Dice) ) )
sampling2(fun = sample,
x = Dice,
params = list(size = 10 ,
replace = TRUE,
prob = rep(1/length(Dice), length(Dice) ) ))
在这两个问题中,矢量化部分都不能正常工作,而且我有点坚持它,因为我还没有找到如何处理它 . 如果有人有想法解决这个问题,那就太棒了!谢谢你们,祝你们度过愉快的一天 .
最好的祝福,
编辑:乍一看,能够在此通用包装器中调用示例函数似乎是多余的 . 但是我目前在算法中多次使用它作为“先验”的形式,并且想要在没有太多代码调整的情况下相对快速地切换到另一个分发 .