我有一個函式,比如 fun(x),這個函式計算一個值并回傳它。然后,使用回傳的值,使用該值運行函式 fun(x)。我想撰寫一個使用此函式的 while 回圈來生成值并將它們存盤在向量中,直到函式生成的值已經出現在向量中。
這是我嘗試過的。
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
}
我似乎無法弄清楚如何正確編碼。任何幫助表示贊賞
uj5u.com熱心網友回復:
像這樣的東西?顯然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)
}
uj5u.com熱心網友回復:
這是一種方法。它每次迭代僅呼叫一次函式,將其值保存在輔助變數中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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/324581.html
上一篇:串列中所有可能的組合
