0

In statistics, there is rejection method to generate a random variable. (but it is not main problem)

I finished the sampling, and want to draw graphics in one screen.

I thought it was an 'add=TRUE' option, and I set it up.

But it showed me a new screen.

I do not know what is wrong.

I'm sorry to post a trivial question, but I have no other place to ask.

nsample=10000
fx = function(x){2*exp(-(x^2)/2)/sqrt(2*pi)}
gx = function(x){exp(-x)}
fxdivgx = function(x){(2*exp(-(x^2)/2)/sqrt(2*pi)/exp(-x))}

grid=seq(0.0,5.0, length.out =1000)
which(fxdivgx(grid)==max(fxdivgx(grid)))
grid[201] #x valuable which fx/gx has maximum value
const = fxdivgx(grid[201])
const
fn = function(x){((2*exp(-(x^2)/2)/sqrt(2*pi))/(exp(-x)*const))}

result2 = list()
result2$candi=rexp(nsample)
result2$targetDen=fn(result2$candi)
result2$keep=ifelse(runif(nsample)<result2$targetDen, TRUE, FALSE)

hist(result2$candi[result2$keep], freq=F, breaks=100)
curve(2*exp(-(x^2)/2)/sqrt(2*pi), add='TRUE', col='red')

This is my code.

When I run this code, the results are printed on different screens.

How do I print two pictures in one screen?

hist(result$candi[result$keep], breaks=100)
curve((2*exp(-(x^2)/2)/sqrt(2*pi)), add=TRUE, col='red')

after plotting these two lines, i got below graphics. enter image description here

Jiwon Kim
  • 139
  • 3
  • 12
  • you don't want `curve`, you want `lines` or `points`, see `?lines` – MichaelChirico Dec 17 '17 at 08:10
  • `lines(seq(0,4,0.1),lapply(seq(0,4,0.1),function(x) 2*exp(-(x^2)/2)/sqrt(2*pi)))`, should do it. Notice that you need to know the range of the x axis though. – DJJ Dec 17 '17 at 08:10
  • The reason is that `curve` uses `plot.default` and `plot.default` doesn't have an `add` argument. [see here for example](https://stackoverflow.com/questions/18262017/why-does-plot-not-respect-add-true#18262244) – DJJ Dec 17 '17 at 08:18
  • @DJJ I'm not sure what you mean... `curve` indeed has an add argument. – MichaelChirico Dec 17 '17 at 10:22
  • 3
    Use `add=TRUE` not `add='TRUE'` ! – Marco Sandri Dec 17 '17 at 10:29
  • @MarcoSandri no it doesn't work. plz see edited post. I can only see horizontal line..... – Jiwon Kim Dec 18 '17 at 10:27
  • 1
    It works. My solution solved your problem, but now you have a different problem. Add `prob=TRUE` inside histogram. See here: https://stackoverflow.com/questions/1497539/fitting-a-density-curve-to-a-histogram-in-r – Marco Sandri Dec 18 '17 at 10:41

0 Answers0