[英]How to Code a Recursive Function by Vector in R?
I have a function: (1 - (x / d)) which d is members of a vector (V) Based on length of the vector, a function will be like this: for example vector is V [2, 3.5, 5, 4.1] so the function would be:我有一个 function: (1 - (x / d))其中 d 是向量的成员 (V) 基于向量的长度,function 将是这样的:例如向量是 V [2, 3.5, 5, 4.1] 所以 function 将是:
[(1-(x/2))*(1-(x/3.5))*(1-(x/5))*(1-(x/4.1))]
if I give it an other vector like [1.5, 2] function would be:如果我给它一个其他向量,例如 [1.5, 2] function 将是:
[(1-(x/1.5))*(1-(x/2))]
that means the function's shape depends on length of my vector and its elements.这意味着函数的形状取决于我的向量及其元素的长度。 I want a code to create this function and then find its maximum by optimize in R.我想要一个代码来创建这个 function,然后通过在 R 中优化找到它的最大值。
Here is a way.这是一种方法。 Function f
returns a function that can be applied to a vector x
. Function f
返回可应用于向量x
的 function 。
f <- function(d) {
force(d)
function(x) prod(1 - x/d)
}
d <- c(1.5, 2)
g <- f(d)
sapply(1:5, g)
#[1] 0.1666667 0.0000000 0.5000000 1.6666667 3.5000000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.