You're looking for the which.min
function, which gives the index corresponding to the least value in the given vector. See ?which.min
. Hence, something like this should give what you want:
Tin <- 5.04
t <- 0.1
sed <- seq(from = 0, to = 0.7, by = 0.001)
i <- which.min(abs(5 + t*sed - Tin))
#[1] 401
sed[i]
#[1] 0.4
Unless I've misunderstood your pseudo code, there seems to be no reason to use a for-loop.
Edit 2:
To answer the comment; it should probably look like this
fun <- function(x, d, sed) { # Some complicated function
return(x*sed^2 + d)
}
myfun <-function(Tin) {
sed <- seq(from = 0, to = 0.7, by = 0.001)
Tou_vec <- fun(x = 1, d = 2, sed = sed) + 5
i <- which.min(abs(Tou_vec - Tin))
return(sed[i])
}
myfun(Tin = 5.5)
#[1] 0
The function which.min
expects a numeric
vector of values and returns the index of the least value. In you code here, you supply a vector of length one, and thus i
always evaluates to 1
. Also you try to return (or at least print) the (first) value from within the for
-loop. This doesn't work and an explicit print
or return
is needed if you insist. I've attempted to rewrite your myfun
in the answer. From your example(s), you do not need a for
-loop.