How to use algebraic formula as an argument in an R function

66 Views Asked by At

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.

1

There are 1 best solutions below

1
user8229029 On

I found a solution as follows:

formula <- '6.1121 * exp(((18.678 - ta/234.5) * ta)/(ta + 257.14)) * 100'

ta = c(20,5,-10)
rh = c(50,40,70)

iterative_Td <- function(formula, ta, rh){
  es <- function(ta){
    parse(text = formula)}

  Td_array <- rep(NA,length(ta))
  ea <- eval(es(ta)) * rh/100

  for (i in 1:length(ea)){
    Td_array[i] = optimize(function(ta){abs(ea[i] - 
        eval(es(ta[i])))}, c(-100,100), tol = 0.00001)$minimum}

  return(Td_array)}

> iterative_Td(formula,ta,rh)
[1]   9.270961  -7.478382 -14.430393