This is an example out of my text which I copied directly but am getting an error every iteration and am unsure how to correct it. The error is "
the condition has length > 1 and only the first element will be used" and my code is:
f <- function(x, sigma) {
if (any(x < 0)) return(0)
stopifnot(sigma > 0)
return((x/sigma^2)*exp(-x^2 / (s*sigma^2)))
}
xt <- x[i-1]
y <- rchisq(1, df = xt)
m <- 10000
sigma <- 4
x <- numeric(m)
x[1] <- rchisq(1, df = 1)
k <- 0
u <- runif(m)
for(i in 2:m) {
xt <- x[i-1]
y <- rchisq(1, df = xt)
num <- f(y, sigma) * dchisq(xt, df = y)
den <- f(xt, sigma) * dchisq(y, df = xt)
if (u[i] <= num/den) x[i] <- y else {
x[i] <- xt
k <- k+1
}
}
print(k)
index <- 5000:5500
y1 <- x[index]
#plot(index, y1, type = "l", main = "", ylab = "x")
The following modified code gives one error:
Error in f(y, sigma) : object 's' not found
You are not sending the value of "s" to the function "f".
No other errors. Is it "s" or '2" ?
----------------------------------------------------------------------------------------
f <- function(x, sigma) {
if (any(x < 0)) return(0)
stopifnot(sigma > 0)
return((x/sigma^2)*exp(-x^2 / (s*sigma^2)))
}
m <- 10000
sigma <- 4
x <- numeric(m)
x[1] <- rchisq(1, df = 1)
k <- 0
u <- runif(m)
xt <- x[i-1]
y <- rchisq(1, df = xt)
for(i in 2:m) {
xt <- x[i-1]
y <- rchisq(1, df = xt)
num <- f(y, sigma) * dchisq(xt, df = y)
den <- f(xt, sigma) * dchisq(y, df = xt)
if (u[i] <= num/den) x[i] <- y else {
x[i] <- xt
k <- k+1
}
}
print(k)
index <- 5000:5500
y1 <- x[index]
#plot(index, y1, type = "l", main = "", ylab = "x")
Get Answers For Free
Most questions answered within 1 hours.