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:
[(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-(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.
Here is a way. Function f
returns a function that can be applied to a vector x
.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.