0

I tried to model this question in order to have a portion of a curve shaded between two values. My code is:

n_samples <- 1e4
p_grid <- seq( from=0 , to=1 , length.out=1000 )
prior <- rep( 1 , 1000 )
likelihood <- dbinom( 6 , size=9 , prob=p_grid )
posterior <- likelihood * prior
posterior <- posterior / sum(posterior)
samples <- sample( p_grid , prob=posterior , size=n_samples , replace=TRUE )


x1 <- 0.5
x2 <- 0.7
dens <- density(samples)
plot(dens)
with(dens, polygon(x=c(x[c(x1,x1:x2,x2)]), y= c(0, y[x1:x2], 0), col="gray")) 

However, I get the error:

Error in xy.coords(x, y, setLab = FALSE) : 'x' and 'y' lengths differ

Am a beginner in R and don't know what needs to be fixed. Any help much appreciated!

Phil
  • 5,491
  • 3
  • 26
  • 61
z8080
  • 459
  • 1
  • 7
  • 19

1 Answers1

0

You're almost there. You need to select the subset of dens where dens$x lies between x1 and x2.

x1 <- 0.5
x2 <- 0.7
dens <- density(samples)

plot(dens)

with(dens, polygon(x = c(x1, x[x > x1 & x < x2], x2), 
                   y = c(0, y[x > x1 & x < x2], 0), col = "gray")) 

enter image description here

Allan Cameron
  • 91,771
  • 6
  • 28
  • 55