【问题标题】:For loop inside a function to create m number of functions函数内部的for循环创建m个函数
【发布时间】:2021-09-08 20:46:32
【问题描述】:

假设我有以下函数和输出:

library('pracma')
xlag= c(1,3,5,8,12,16,19,20,22,24)
f1 <- function(beta){ 
  xlag[1]*exp(beta[1] * 1)/(exp(beta[1] * 1)+exp(beta[1] * 2)+exp(beta[1] * 3)) + 
  xlag[2]*exp(beta[1] * 2)/(exp(beta[1] * 1)+exp(beta[1] * 2)+exp(beta[1] * 3)) +
  xlag[3]*exp(beta[1] * 3)/(exp(beta[1] * 1)+exp(beta[1] * 2)+exp(beta[1] * 3))
}
pracma::jacobian(f1,c(1)) 

          [,1]
[1,] 0.8488091

我在函数中写了几个 for 循环,这样我就可以为任何值 s 扩展模型。

h <-function(beta){
  s = 1:3
  xlag= 1:9
  n <-c()
  for (i in s) {
    n[i] <- exp(beta[1] * s[i])
  }
  sal <-sum(n)
  z <-c()
  for (i in s) {
    z[i] <- xlag[i]*exp(beta[1] * s[i])/sal
  }
  sum(z) 
}
pracma::jacobian(h,c(1))

          [,1]
[1,] 0.8488091

现在我想为 xlag[1:3]、xlag[4:6] xlag[7:9] 写 f。 这样雅可比矩阵就变成了一个 1 列 3 行的矩阵。其中第一个条目是上面指定的条目。第二个条目是:

f2 <- function(beta){ 
  xlag[4]*exp(beta[4] * 1)/(exp(beta[1] * 1)+exp(beta[1] * 2)+exp(beta[1] * 3)) + 
  xlag[5]*exp(beta[5] * 2)/(exp(beta[1] * 1)+exp(beta[1] * 2)+exp(beta[1] * 3)) +
  xlag[6]*exp(beta[6] * 3)/(exp(beta[1] * 1)+exp(beta[1] * 2)+exp(beta[1] * 3))
}
pracma::jacobian(f2,c(1)) 
         [,1]
[1,] 1.697618

第三条:

f3 <- function(beta){ 
  xlag[7]*exp(beta[4] * 1)/(exp(beta[1] * 1)+exp(beta[1] * 2)+exp(beta[1] * 3)) + 
  xlag[8]*exp(beta[5] * 2)/(exp(beta[1] * 1)+exp(beta[1] * 2)+exp(beta[1] * 3)) +
  xlag[9]*exp(beta[6] * 3)/(exp(beta[1] * 1)+exp(beta[1] * 2)+exp(beta[1] * 3))
}
pracma::jacobian(f3,c(1))

         [,1]
[1,] 0.706992

所以我希望 h 输出:

          [,1]
[1,] 0.8488091
[2,] 1.697618
[3,] 0.706992

雅可比函数的结构如下

library('pracma')
jacobian(f, x0, heps = .Machine$double.eps^(1/3), ...)
f: m functions of n variables.
x0: Numeric vector of length n.
heps: This is h in the derivative formula.
jacobian(): Computes the derivative of each function f_j by variable x_i separately, taking the discrete step h.

所以我需要一个变量的 3 个函数 f1,f2,f3。产生一个 1 列和 3 行的矩阵。 谁能帮我重写 h 以获得所需的输出?

【问题讨论】:

  • 为什么不将 f 定义为 f(beta, lag_start)?然后xlag[lag_start]...xlag[lag_start+2]
  • 嗯。然后我必须在之后手动将它们添加在一起

标签: r function for-loop


【解决方案1】:

我找到了解决办法。

h <-function(beta){
  s = 1:3
  xlag #total set of xlag variables
  u =1:(length(xlag)-length(s)) #basis for loop
  n <-c()
  for (i in s) {
    n[i] <- exp(beta[1] * s[i]) #nominator expo almon 
  }
  sal <-sum(n) #denominator expo almon
  z <-c()
  for (i in s) {
    z[i] <- exp(beta[1] * s[i])/sal #expoalmon
  }
  final <-c()
  for (i in u) {
    final[i] <- sum(xlag[(i):(i+2)]*z[1:3])
  }
  final
}
pracma::jacobian(h,c(1)) 

【讨论】:

    猜你喜欢
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多