Lets assume
x = c(1, 2, 3.5, 4, 6, 7.5, 8, 9, 10, 11.5, 12)
y = c(2.5, 6.5)
I = split(x, findInterval(x, y))
f = function(I$'i', x) {
d = pmax(outer(x, I$'i', "-"), 0)
colSums(d - d^2/2)
}
I want to calculate the value of f(I$’i’, x) in each values of each interval and then find which I$’i’ actual value have the maximum value of f(I$’i’, x ) in each interval. for example if we have three intervals , my result should be three values of x which f(I$’i’, x) is maximum in each interval. how can i find these values?
In addition, it should be mentioned that in each iteration of my code the value of vector y changes.
I wrote this code but i can not find the actual values of the maximum value in each interval:
for(i in 0:length(I)-1){
max.value = I$'i'[which.max(f(I$'i', x))]
}
and i got this error:
Error in pmax(outer(x, I, “-“), 0) :
cannot mix 0-length vectors with others
The problem is attempting to index the
ith element of the list. DoingI$'i'is trying to get the element of the list corresponding to the string'i', which doesn’t exist:To fix this, you should index a list using the
[[..]]notation (which indexes them in order, i.e.I[[1]]=I$'0'):Assuming that
fis just meant to take a vector (rather than an index intoI), its definition should be something like:And the loop like:
Note that you can iterate directly over the elements of a list, you don’t need to index each one individually, so we could also do:
(Also, you might want something slightly different to what you have, since in each loop
max.valueis overwritten.)