我编写了一个由R包的另一个函数多次运行的函数,但我希望每次使用该函数时都能访问我函数的一些内部参数,但是&当我的功能被R包的功能使用时,不可能这样做。
library(pracma)
model <- function(t,x,params){
y0 <- x[1]
y1 <- x[2]
y2 <- x[3]
y3 <- x[4]
ry <- params[1]
mu <- params[2]
d0 <- params[3]
ay <- params[4]
d1 <- params[5]
by <- params[6]
d2 <- params[7]
cy <- params[8]
d3 <- params[9]
m <- rep(0,4)
m[1] = ((ry*(1-mu)) - d0) * y0 #####I want to store the value of y0
m[2] = (ay * y0) - (d1 * y1) #######and y1
m[3] = (by * y1) - (d2 * y2) #######and y2
m[4] = (cy * y2) - (d3 * y3) #######and y3, for each time ode23 calls my function
return(m)
}
ay = 1.6 / 100
d1 = 0.008
by = 10 / 750
d2 = 0.05
cy = 100
d3 = 1
y_0 = 250000
y_1 = (ay*y_0) / d1
y_2 = (by*y_1) / d2
y_3 = (cy*y_2) / d3
x <- ode23(model, y0 = c(y0=y_0, y1=y_1, y2=y_2, y3=y_3), t0=0,tf=400,
params = c(0.008,4*10^-8,0.003,1.6/100,0.008,10/750,0.05,100,1))
答案 0 :(得分:0)
您可以递归存储值:
y0list<-NULL ##only do this once to initialize the lists. If this is running
y1list<-NULL ## inside a function, make sure the environment is correct.
y2list<-NULL ## if concerned, you should be ok if you initialize in the global env.
y3list<-NULL
model <- function(t,x,params){
y0 <- x[1]
y0list<<-c(y0list, y0)
y1 <- x[2]
y1list<<-c(y1list, y1)
y2 <- x[3]
y2list<<-c(y2list, y2)
y3 <- x[4]
y3list<<-c(y3list, y3)
ry <- params[1]
mu <- params[2]
d0 <- params[3]
ay <- params[4]
d1 <- params[5]
by <- params[6]
d2 <- params[7]
cy <- params[8]
d3 <- params[9]
m <- rep(0,4)
m[1] = ((ry*(1-mu)) - d0) * y0 #####I want to store the value of y0
m[2] = (ay * y0) - (d1 * y1) #######and y1
m[3] = (by * y1) - (d2 * y2) #######and y2
m[4] = (cy * y2) - (d3 * y3) #######and y3, for each time ode23 calls my function
return(m)
}
检查此示例:
y0list<-NULL #outside the function
y1list<-NULL
foo.func<-function(data){
sums<-NULL
for(i in 1:length(data)){
y0<-data[i]
y0list<<-c(y0list, y0)
y1<-data[sample(1:length(data),1)]
y1list<<-c(y1list, y1)
sums[i]<-y0+y1
}
return(sum(sums))
}
foo.func(1:10)
[1] 108
y0list
[1] 1 2 3 4 5 6 7 8 9 10
y1list
[1] 7 8 1 6 4 1 3 10 6 7
小心这些,因为我怀疑它会减慢功能,特别是如果它被多次迭代。
答案 1 :(得分:0)
您是否调查了输出x
?
您的变量y0
,y1
,y2
和y3
已存储!
您可以通过x$y
加载它们。
head(x$y)
y0 y1 y2 y3
[1,] 250000.0 500000.0 133333.3 13333333
[2,] 258578.2 500452.2 133347.0 13333333
[3,] 262670.0 500968.3 133372.2 13338593
[4,] 266889.3 501688.2 133418.4 13334541
[5,] 270474.3 502441.9 133476.5 13352665
[6,] 274911.7 503545.7 133574.8 13334574