我正在R中编写一个函数:
MH <- function(Nsim,var,initial) {
Total <- 0
X=rep(runif(1),Nsim)
X[1]=initial
for (i in 2:Nsim){
Y=X[i-1]+rnorm(1, mean=0, sd=sqrt(var))
alpha= fx(Y)/fx(X[i-1])
u <- runif(1)
X[i]=X[i-1]+(Y-X[i-1])*(u<alpha)
Total=Total+as.numeric(u<alpha)
}
accept=Total/Nsim
accept
}
我希望我的函数输出为'accept',同时将矢量X直接保存到工作区中而不显示它,这样我以后可以用X做事。 我知道这是一个基本问题,但有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
这样的事情
MH <- function(Nsim,var,initial) {
Total <- 0
X=rep(runif(1),Nsim)
X[1]=initial
for (i in 2:Nsim){
Y=X[i-1]+rnorm(1, mean=0, sd=sqrt(var))
alpha= fx(Y)/fx(X[i-1])
u <- runif(1)
X[i]=X[i-1]+(Y-X[i-1])*(u<alpha)
Total=Total+as.numeric(u<alpha)
}
accept=Total/Nsim
# put output into a list and give it class MH
output <- list(accept = accept, X = X)
class(output) <- "MH"
output
}
# Write a custom print function for objects of
# class "MH"
print.MH <- function(x, ...){
print(x[["accept"]])
}
out <- MH(10, 1, 1)
out # only prints the acceptance rate
out$accept # but can access accept
out$X # and X individually