我有一个函数,比如fun(x),这个函数计算一个值并返回它。然后,使用返回值,用该值运行函数fun(x)。我想编写一个while循环,使用这个函数来生成值并将它们存储在vector中,直到从函数生成的值已经出现在vector中。
这就是我所尝试的。
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
}
我似乎不知道如何正确地编码。任何帮助都是感激的
像这样?显然,sample()
在while
语句中返回的数字与循环中的不同,但我假设你的函数不是随机的?
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)
}
这里有一个方法。它每次迭代只调用函数一次,并将其值保存在辅助变量y
中。当向量满时也有一个停止条件。
函数fun
是一个用于只返回一个泊松随机数的测试的示例。
我已将起始值更改为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