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
  • 7,287
  • 3
  • 36
  • 66
z8080
  • 571
  • 3
  • 7
  • 23
  • Normally we use integers to index vectors. I'm not sure what you expect `x1:x2` to be when you have `x1 <- 0.5` and `x2 <- 0.7`, but what you get is `0.5`. What do expect `y[0.5]` to be? I think it's `NULL`. – Gregor Thomas Nov 11 '21 at 16:06
  • Maybe you want `x[x1 <= x & x <= x2]` and similar for `y`? – Gregor Thomas Nov 11 '21 at 16:07
  • My x axis ranges 0 to 1, so I was thinking of x1 and x2 as actual values on the x axis, rather than vector indices. – z8080 Nov 11 '21 at 17:07

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
  • 147,086
  • 7
  • 49
  • 87