Initialize vector using the ifelse function in R

I'm trying to run the next algorithm in R:

simulation <- function(n){
  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) 
    y <- rnorm(2, mean = w, sd = S1)  #Also this line gives a non-zero value to y 
    alfa <- (f(y))/(f(w))
    ifelse(runif(1)<alfa,x<-y,x<-w) //Here the variables y and w are a two dimension zero vector. 

I don't understand why at the second "ifelse" the vectors w and y are equal to (0,0). Maybe there is another way to initialize the vector x. But I don't get how the first "ifelse" works fine. Any suggestions would be great!

Welcome to the community!

I'm not on laptop right now to answer your question, but I just want to point out that you are using ifelse in a very unusual way. At least I haven't seen this way before.

This is the usual way:

w <- ifelse(i==0, x0, x)

Also in your code, alfa is a scalar. How are you picking the (n+1)-th element?

1 Like


I agree with @Yarnabrina that the functions you are using are a bit odd. Also, there are missing parameters like the function "h(), g()" and the variable "S1".

Try to create a reprex so we can better work with your code. A reprex consists of the minimal code and data needed to recreate the issue/question you're having. You can find instructions how to build and share one here:

Good luck,

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.