I have a long list of different formulations for atmospheric vapor pressure. I would like to make evaluation of these easier by writing a function that uses the formula as an argument, and finds a solution with the optimization function. The code without a function looks like this (as an example):
es <- function(ta){6.1121 * exp(((18.678 - ta/234.5) * ta)/(ta + 257.14)) * 100}
ea <- es(ta) * rh/100
result <- optimize(function(ta){abs(es - es(ta))}, c(-100,100), tol = 0.00001)$minimum
The formula inside the brackets in the "es" function is what I want to be used as an argument. Some code I've tried looks like this:
formula <- '6.1121 * exp(((18.678 - ta/234.5) * ta)/(ta + 257.14)) * 100'
iterative_Td <- function(formula, ta, rh){
es <- function(ta){
substitute(formula)}
ea <- es(ta) * rh/100
return(optimize(function(ta){abs(ea - es(ta))}, c(-100,100), tol = 0.00001)$minimum)}
How do I reference the formula in the iterative_Td function to make this work? I've tried various configurations of quote, eval, and substitute. None of them work. Thank you.
EDIT: to test, a value of 20 for ta and 50 for rh is good. You should get a Td value of 9.2506.
I found a solution as follows: