If I understood the problem correctly you are trying to simulate a vector containing 2 values which in the function is named as alfa.
Also in each iteration w and y are not equal (0, 0) it is updating as you have stated in the function. The above function only returns the nth value of alfa.
alfa only has 2 elements in each iteration and return(alfa[n]) with return value from the last iteration only.
I have created two simple function named h and g assuming you will also have similar ones and defined sd as 1.
Made a small tweak to your query to get n number of vectors containing 2 elements each.
h <- function(x) {
x ^ 2
}
g <- function(x) {
x ^ 3
}
simulation <- function(n, S1 = 1, seed = 123){
f <- function(x){.7*h(x)+.3*g(x)}
x <- vector("numeric", 2)
w <- vector("numeric", 2)
x0 <- c(3, 3)
for(i in 0:n){
ifelse(i==0, w <- x0, w <- x) # After this line w=(3,3) (on the first iteration)
set.seed(seed)
y <- rnorm(2, mean = w, sd = S1) # Also this line gives a non-zero value to y
alfa <- (f(y))/(f(w))
set.seed(seed + 1)
ifelse(runif(1) < alfa, x <- y, x <- w) # Here the variables y and w are a two dimension zero vector.
print(alfa)
}
}
simulation(3)
Output from above query
[1] 0.5917627 0.8156456
[1] 0.5236186 0.8027823
[1] 0.4268981 0.7878858
[1] 0.2798218 0.7704123
Or else if you want to store the simulation in alfa and then return the complete alfa without printing each iteration then you can use the below function which creates a matrix for alfa:
simulation <- function(n, S1 = 1, seed = 123){
f <- function(x){.7*h(x)+.3*g(x)}
x <- vector("numeric", 2)
w <- vector("numeric", 2)
x0 <- c(3, 3)
alfa <- matrix(0, nrow = n + 1, ncol = 2) # matrix of zeros
for(i in 0:n){
ifelse(i==0, w <- x0, w <- x) # After this line w=(3,3) (on the first iteration)
set.seed(seed)
y <- rnorm(2, mean = w, sd = S1) # Also this line gives a non-zero value to y
alfa[i + 1, ] <- (f(y))/(f(w))
set.seed(seed + 1)
ifelse(runif(1) < alfa[i + 1, ], x <- y, x <- w) # Here the variables y and w are a two dimension zero vector.
}
return(alfa)
}
simulation(3)
Output from the above query
[,1] [,2]
[1,] 0.5917627 0.8156456
[2,] 0.5236186 0.8027823
[3,] 0.4268981 0.7878858
[4,] 0.2798218 0.7704123
I have used alfa[i + 1, ] since indexing in R starts from 1 and not 0.