Home > OS >  While loop that stores values in a vector and stops when a value is already in the vector [R Program
While loop that stores values in a vector and stops when a value is already in the vector [R Program

Time:10-19

I have a function, say fun(x), this function calculates a value and returns it. Then, using the returned value, run the function fun(x) with that value. I would like to code a while loop that uses this function, to generate values and store them in a vector, until the generated value from the function has already appeared in the vector.

This is what I have attempted.

x <-1 #initial value to run the function with
vec <-numeric(100) #create an empty vector to store the values
k <- 0 # have a counter for the vector position

while((fun(x) %in% vec) != TRUE){ #this while loop with run until the value from the function is already in the vector
  k<- k  1 #increase counter 
  vec[k] <- fun(x) #run the function, store that value
  x <- vec[k] #set x as the stored value 
  
}

I cannot seem to figure out how to code this properly. Any help is appreciated

CodePudding user response:

Something like this? Obviously sample() will return different numbers in the while statement than in the loop, but I assume your function isn't random?

sample(1:10,1)
vec <- c() ## empty vector
x=10
while(!sample(1:x,1) %in% vec){
  x=sample(1:x,1)
  vec <- c(vec,x)
}

CodePudding user response:

Here is a way. It calls the function only once per iteration, saving its value in an auxiliary variable y. There is also a stop condition when the vector is full.
The function fun is an example meant for tests only returning one Poisson random number.

I have changed the starting value to x <- 10.

fun <- function(x) rpois(1, x)

x <- 10           # initial value to run the function with
n <- 100L         # results vector length
vec <- numeric(n) # create an empty vector to store the values
k <- 0L           # have a counter for the vector position
while(!((y <- fun(x)) %in% vec) && k < n){
  k <- k   1L
  vec[k] <- y
  x <- y
}
vec
  • Related