2017-04-09 110 views
0

我知道這是一個非常基本的問題,很抱歉佔用大家的時間。我創建了一個函數,但想要取得這些結果,並再次將其應用於該函數(我試圖模擬增長)。如何獲取函數的結果並將其應用於R中的函數?

我不認爲我想要使用循環,因爲我需要的值來自函數。我也不認爲它適用,因爲我需要從函數中提取值。

這裏是我的功能

initial<-c(36.49) 
second<-NULL 

growth <- function(x){ 
second <- (131.35-(131.35 -x)*exp(-0.087)) 
} 
second<-growth(initial) 
third<-growth(second) 
fourth<-growth(third) 
fifth<-growth(fourth) 
sixth<-growth(fifth) 
seventh<-growth(sixth) 

這裏就是我現在所做的,但你可以看到我會繼續這樣做了,並沿此線再次

+0

非常感謝你!現在我可以在幾秒鐘內模擬100多年! – user3014943

回答

0

您可以使用循環。就在輸出存儲在向量:

# initial value 
initial<-c(36.49) 

# dont need this i think 
# second<-NULL 

# create a holding vector fro result 
values <- vector() 

# assign 
values[1] <- initial 

# your function 
growth <- function(x){ 
    second <- (131.35-(131.35 -x)*exp(-0.087)) 
} 

# start a loop; you start with 2 
for(i in 2:7){ 

    # then access the previous value using i - 1 
    # then store to the next index, which is i 
    values[i] <- growth(values[i - 1]) 
} 

這也應該這樣做。

0

東西也許可以幫助

x <- 1 
try <- function(x) x <<- x+1 
for(i in 1:5) try(x) 
相關問題