2017-04-09 65 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)