小编Lud*_*win的帖子

试图不流泪地复制贝叶斯统计数据:采样-重采样的视角,但失败了

我试图不流泪地复制贝叶斯统计论文中的三个数字:采样重采样视角,可以在这里找到:http ://hedibert.org/wp-content/uploads/2013/12/1992SmithGelfand.pdf 我的目标是复制第 5 节的结果。这是我的代码:

theta1<-runif(1000,0,1)
theta2<-runif(1000,0,1)
theta<-cbind(theta1,theta2)
theta<-as.data.frame(theta)

plot(theta1,theta2)

n1<-c(5,6,4)
n2<-c(5,4,6)
y<-c(7,5,6)

l<-rep(NA,nrow(theta))

for (i in 1:nrow(theta)){
  
  llh.1.store<-rep(NA,4)
  for (j in 2:5){
    llh.1.store[j-1]<-(factorial(n1[1])/(factorial(j)*factorial(n1[1]-j)))*(factorial(n2[1])/(factorial(y[1]-j)*factorial(n2[1]-y[1]+j)))*(theta[i,1]^j)*((1-theta[i,1])^(n1[1]-j))*(theta[i,2]^(y[1]-j))*((1-theta[i,2])^(n2[1]-y[1]+j))
  }
  llh1<-sum(llh.1.store)
  
  llh.2.store<-rep(NA,5)
  for (x in 1:5){
    llh.2.store[x]<-(factorial(n1[2])/(factorial(x)*factorial(n1[2]-x)))*(factorial(n2[2])/(factorial(y[2]-x)*factorial(n2[2]-y[2]+x)))*(theta[i,1]^x)*((1-theta[i,1])^(n1[2]-x))*(theta[i,2]^(y[2]-x))*((1-theta[i,2])^(n2[2]-y[2]+x))
  }
  llh2<-sum(llh.2.store)
  
  llh.3.store<-rep(NA,5)
  for (t in 0:4){
    llh.3.store[t+1]<-(factorial(n1[3])/(factorial(t)*factorial(n1[3]-t)))*(factorial(n2[3])/(factorial(y[3]-t)*factorial(n2[3]-y[3]+t)))*(theta[i,1]^t)*((1-theta[i,1])^(n1[3]-t))*(theta[i,2]^(y[3]-t))*((1-theta[i,2])^(n2[3]-y[3]+t))
  }
  llh3<-sum(llh.3.store)
  
  l[i]<-prod(llh1,llh2,llh3)
}

q<-l/sum(l)
post.theta<-sample_n(theta,1000,replace=TRUE,weight=q)

ggplot(post.theta) +
  aes(x = theta1, y = theta2) +
  geom_point(
    shape = "circle",
    size = 1.85,
    colour = "#440154"
  ) +
  labs(title = "Sample from Posterior") +
  ggthemes::theme_few()
Run Code Online (Sandbox Code Playgroud)

但它不会生成与图 2 相同的图。任何人都可以告诉我我做错了什么吗?

statistics r bayesian

3
推荐指数
1
解决办法
257
查看次数

如何在 dplyr - if_else 中编写多个“或”条件?

这可能是基本的。考虑一个数据框:

df<-data.frame(year=c(2006:2015),
               one=rep(2010,10),
               two=rep(2011,10),
               three=rep(2012,10))
Run Code Online (Sandbox Code Playgroud)

其中one是事件一发生的年份,two是事件二发生的年份,three是事件三发生的年份。我想构造一个变量ha,如果这些事件发生最多 2 年,则该变量取值 1,否则取值 0。

例如,在 2009 年,这些事件都没有发生,因此ha2009 年应该为 0。在 2015 年,距离事件三发生已有 3 年,距离事件一发生已有 5 年,因此ha应该为 0。但在 2011 年,事件一发生了去年发生,事件二刚刚发生,所以ha2011 年应该是 1。

最终结果应如下所示ha

0 0 0 0 1 1 1 1 1 0
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试使用if_elsedplyr 来评估多个“或”条件时,我未能获得所需的结果。这是我的代码:

df<-df%>%
  mutate(
    ha=if_else(year-one%in%c(0,1,2)|year-two%in%c(0,1,2)|year-three%in%c(0,1,2),1,0)
  )
Run Code Online (Sandbox Code Playgroud)

我想知道我的错误在哪里。

r dplyr

0
推荐指数
1
解决办法
73
查看次数

标签 统计

r ×2

bayesian ×1

dplyr ×1

statistics ×1